- C# 프로그램에서 Python 코드 실행하는 방법 
//--------------------- 
// python 실행파일을 통한 실행 
// C# 코드
		public string run_cmd(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = "파이썬 실행파일 경로";//@"C:\ProgramData\Miniconda3\python.exe";
            start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);
            start.UseShellExecute = false;// Do not use OS shell
            start.CreateNoWindow = true; // We don't need new window
            start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
            start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
                    string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
                    
                    return result;
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            var ret = this.run_cmd("test.py", "1");
            Debug.WriteLine(ret);
        }
//------------------------------- 
//Python 코드
import os
import sys
import time
import traceback
import argparse
def main(arg1):
	#print(arg1, sys.argv)
	if arg1 == "1":
		print("1")
	else:
		print("0")
            
#  main top-level start program            
if __name__ == '__main__':   
    arg1 = sys.argv[1]
    main(arg1)
//------------------------------------------------- 
// 실행방법 2 
IronPython 사용
IronLanguages / ironpython3
https://github.com/IronLanguages/ironpython3 
//------------------------ 
//참고 
https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5 
https://medium.com/@ernest.bonat/using-c-to-run-python-scripts-with-machine-learning-models-a82cff74b027 
https://stackoverflow.com/questions/11779143/how-do-i-run-a-python-script-from-c 
반응형
    
    
    
  'Code > C#' 카테고리의 다른 글
| VS 닷넷 코어에서 버튼 콘트롤이 보이지 않는 문제 해결 방법 (0) | 2020.08.03 | 
|---|---|
| [C#] C# 에서 자바스크립트 코드 실행 (0) | 2020.05.04 | 
| [C#] C#에서 PHP 함수 코드 사용하기 (0) | 2020.05.04 | 
| [C#] System.Management.ManagementException: Access denied 에러 해결 방법 (0) | 2020.02.10 | 
| C# 크롬 브라우저 내장하기 (0) | 2020.02.01 | 










