2020년 2월 13일 목요일

C#에서 Python 연동( python.exe를 이용해 .py 파일 직접 실행)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
예시

using System;
using System.Diagnostics;
    class Program
    {
        static void Main(string[] args)
        {
            //가상환경 파이썬 exe를 직접 실행해서 파이썬 코드가 실행
            var psi = new ProcessStartInfo();

            string input_0 = args[0]; // 인자1
            string input_1 = args[1]; // 인자2
            string input_2 = args[2]; // 인자3
            string input_3 = args[3]; // 인자4
            psi.FileName = @"C:\github_local\rist_svn\scheduling\rist_env\Scripts\python.exe"//파이썬 가상환경 설치 경로
            psi.Arguments = string.Format(@"C:\github_local\rist_svn\scheduling/{0}.py {1} {2} {3} ", input_0, input_1, input_2, input_3); //파일경로
            //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))
            {
                errors = process.StandardError.ReadToEnd();
                results = process.StandardOutput.ReadToEnd();
            }
            // Console.WriteLine(errors);
            Console.WriteLine(results);
        }
    }

실적용
테스트 용으로 로컬 C# 프로젝트의 경로에 파이썬을 직접 옮겨서 테스트

c#전용인가?
Application.StartupPath(실행파일이 있는 경로까지 실행파일 이름을 포함하지 않는 path)

//가상환경 파이썬 exe를 직접 실행해서 파이썬 코드가 실행!! 
                var psi = new ProcessStartInfo();
                string input_0 = "인자1"// 인자1
                string input_1 = "인자2"// 인자2
                string input_2 = "인자3"// 인자3
                psi.FileName = Application.StartupPath + "\\Python_3.6.5\\python.exe"//파이썬 가상환경 설치 경로
                psi.Arguments = Application.StartupPath + "./test.py "+input_0+" "+input_1+" "+input_2; //파일경로
//3) Proecss configuration 
//4) return value def
test.py파일경로와 args을 psi.Arguments에 적용
//결과를 텍스트로 표현
RxBox.AppendText("Result : " + results + Environment.NewLine);
psi.Arguments 유의사항
  
" ./test.py" == 에러 띄워쓰기 -> "./test.py" 이런식으로 붙여야함
모든 args도 마찬가지로 띄워쓰기 해야함
cs

댓글 없음:

댓글 쓰기

git rejected error(feat. cherry-pick)

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