2016-08-13 2 views
0

파이썬 프로그램을 호출하고 C#을 사용하여 호출 될 때 자동으로 실행되도록하고 싶습니다. 나는 프로그램을 열심히 열었지만 그것을 어떻게 실행하고 결과를 얻었 는가. 그것은 내 마지막 해 프로젝트가 친절하게 도와입니다 out.Here 내 코드입니다 :거기에 C#을 사용하여 파이썬 프로그램을 실행하는 방법은 무엇입니까?

시험 :

Process p = new Process(); 
     ProcessStartInfo pi = new ProcessStartInfo(); 
     pi.UseShellExecute = true; 
     pi.FileName = @"python.exe"; 
     p.StartInfo = pi; 

     try 
     { 
      p.StandardOutput.ReadToEnd(); 
     } 
     catch (Exception Ex) 
     { 

     } 
+0

[C#에서 python 스크립트 실행] 가능한 복제본 (http://stackoverflow.com/questions/11779143/run-a-python-script-from-c-sharp) –

+0

나는 이것을 시도했다. 그리고 훨씬 더하지만 모두 예외없이 "내게 __future__라는 모듈이 없다"는 생각이 들지 않으면이 모든 것을 나에게 친절하게 안내해 준다. 어쨌든 고맙습니다. –

+0

작업 디렉토리 pi.WorkingDirectory = @ "your_working_directory_to_main_python_script"를 정의하십시오. 내가 사소한 변경과 동일한 링크에서 http://stackoverflow.com/a/11779234/3142139 사용, 내 코드를 더 일찍 게시 할 것입니다, 그리고 그것은 일하고 있어요 :) –

답변

0

다음 코드 모듈 및 반환 결과

class Program 
{ 
    static void Main(string[] args) 
    { 
     RunPython(); 
     Console.ReadKey(); 

    } 

    static void RunPython() 
    { 
     var args = "test.py"; //main python script 
     ProcessStartInfo start = new ProcessStartInfo(); 
     //path to Python program 
     start.FileName = @"F:\Python\Python35-32\python.exe"; 
     start.Arguments = string.Format("{0} ", args); 
     //very important to use modules and other scripts called by main script 
     start.WorkingDirectory = @"f:\labs"; 
     start.UseShellExecute = false; 
     start.RedirectStandardOutput = true; 
     using (Process process = Process.Start(start)) 
     { 
      using (StreamReader reader = process.StandardOutput) 
      { 
       string result = reader.ReadToEnd(); 
       Console.Write(result); 
      } 
     } 
    } 
} 

테스트 스크립트를 호출 파이썬 스크립트를 실행 평

import fibo 
print ("Hello, world!") 
fibo.fib(1000) 

모듈 : fibo.py

def fib(n): # write Fibonacci series up to n 
    a, b = 0, 1 
    while b < n: 
     print (b), 
     a, b = b, a+b 
관련 문제