2020년 8월 26일 수요일

c#에서 외부파일 실행하기

 리스트 과제에서 외부 파이선을 실행해야하는 상황이 생겨서 해본것


%주의 -> 왠만한 에러는 콘솔창에 나오게 할수 있지만 

나오지 않는 에러도 있으니 차근차근 디버깅 해야함(호출하는곳,실행되는곳)

실행되는 원본(파이썬)에서는 에러 없이 되지만 호출하여서 인자를 받아서 실행할때는 안될수도있다.

인자를 통하여 외부프로그램이 돌아가는지 하나씩 확인하여 디버깅하여야한다.




//호출부분


public void PythonStart(string key, string data, int TotalLen, string PATH_p)

        {

            var psi = new ProcessStartInfo();

            Console.WriteLine("PATH_p:" + PATH_p);

            Console.WriteLine("data:" + data);

            //string psi_args = PATH_p + data; //경로를 지정한 실행파일


            string[] dataitem = data.Split(' ');

            dataitem[3] =dataitem[3].Replace("'", "");

            dataitem[4] =dataitem[4].Replace("'", "");

            dataitem[5] = dataitem[5].Replace("'", "");

            string newresult = "";

            for (int i = 0; i < dataitem.Length; i++)

            {

                newresult += dataitem[i]+" ";

            }

            string psi_args = PATH_p + newresult; //경로를 지정한 실행파일

            //string psi_args = PATH_p + data; //경로를 지정한 실행파일

            Console.WriteLine("psi_args:" + psi_args);

            psi.FileName = @"C:\scheduler\rist_env\Scripts\python.exe"; //파이썬 가상환경 설치 경로

            psi.Arguments = psi_args; //파일경로

            //psi.Arguments = string.Format("\"{0}\"\"{1}\"", PATH_p, data);


            //3) Proecss configuration

            psi.UseShellExecute = false;

            psi.CreateNoWindow = true;

            psi.RedirectStandardOutput = true;

            psi.RedirectStandardError = true;


            //4) return value def

            var errors = ""; // 출력은 하지 않습니다.

            var results = "";


            //using (var process = Process.Start(psi))

            //using (var process = System.Diagnostics.Process.Start(psi))

            using (var process = Process.Start(psi))

            {

                Console.WriteLine("프로세스 실행 하고 기다리기!!");

                //process.WaitForExit();


                results = process.StandardOutput.ReadToEnd();

                errors = process.StandardError.ReadToEnd();

                RxBox.AppendText("Error : " + errors + Environment.NewLine);

                RxBox.AppendText("Result : " + results + Environment.NewLine);

                //while (process.StandardOutput.Peek() > -1)

                //{


                //    process.StandardOutput.Close();

                //    RxBox.AppendText("break!!!! process.StandardOutput.Peek()");

                //    break;

                //}

                //while (process.StandardError.Peek() > -1)

                //{


                //    process.StandardError.Close();

                //    RxBox.AppendText("process.StandardError.Peek()");

                //    break;

                //}


                //using (StreamReader reader = process.StandardOutput)

                //{

                //    results = reader.ReadToEnd();

                //    Console.WriteLine(results);

                //}

                //using (StreamReader reader = process.StandardError)

                //{

                //    errors = reader.ReadToEnd();

                //    Console.WriteLine(errors);

                //}

            }

            

            RxBox.AppendText("Error : " + errors + Environment.NewLine);

            RxBox.AppendText("Result : " + results + Environment.NewLine);

        }







//키받아서 외부로 보내는것 관리하는 함수

try

                    {

                        switch (key)

                        {

                            case "predict_schedule_to_db":

                                Console.WriteLine("predict_schedule_to_db 요청 들어옴");

                                //path = @"C:\scheduler\pzpy\rist\app\predict_schedule_to_db.py";

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\predict_schedule_to_db.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;

                            case "verify_model":

                                Console.WriteLine("verify_model 요청 들어옴");

                                //path = @"C:\scheduler\pzpy\rist\app\verify_model.py";

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\verify_model.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;


                            case "test_hubiz":

                                Console.WriteLine("test_hubiz 요청 들어옴");

                                path = $"\"C:\\scheduler\\pzpy\\rist\\app\\test_hubiz.py\"";

                                Form1.instance.PythonStart(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                //Form1.instance.PythonTest(key, value.Substring(1, value.Length - 1), e.RawData.Length, path);

                                break;

                        }

                        //맨앞에 공백 하나 제거

                        //Form1.instance.PythonTest(key, value.Substring(1, value.Length-1), e.RawData.Length, path);

                        

                    }

                    catch (Exception ex)

                    {

                        MessageBox.Show(ex.ToString());

                        return;

                    }

댓글 없음:

댓글 쓰기

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...