- 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


반응형
Posted by codens