본문 바로가기
프로그래밍/C#

[C#] C#에서 python 스크립트를 불러오고 argument 주고받기

by 왕초보 개발자 2021. 3. 26.
728x90

예시로 사용할 간단한 python 코드

# python version : 3.7.5
import pyautogui
import sys

# c#에서 가져온 arguments는 "sys.argv[index]" 로 사용함
# index는 1부터 시작
a = pyautogui.alert(text=str(sys.argv[2]), title=sys.argv[1], button="ok")

# python 스크립트의 가장 마지막 줄에 C#에서 리턴받기 원하는 값을 print로 던져줌
print("python_result")

 

// 실행시키는 python version : 3.7.5
// anaconda로 실행시키면 실행 안될 수 있음

var psi = new System.Diagnostics.ProcessStartInfo();

// python 설치 경로
psi.FileName = @"C:\Program Files\Python37\python.exe";

// python 스크립트 파일 경로
var script = @"C:\Users\user\Desktop\example.py";
// arguments들
var arg1 = "1234";
var arg2 = "5678";

// 스크립트 파일과 arguments 입력 - 변경시 추가/제거
psi.Arguments = $"\"{script}\" \"{arg1}\" \"{arg2}\"";

psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;

var errors = "";
var results = "";

using(var process = System.Diagnostics.Process.Start(psi)){
  errors = process.StandardError.ReadToEnd();
  results = process.StandardOutput.ReadToEnd();  // python에서 받아오는 값
}

728x90