2016-08-13 2 views
0

私はPythonプログラムを呼び出して、呼び出されると自動的にC#を使って実行したいと思っています。私はプログラムを開こうと努力しましたが、それを実行する方法と出力を得る方法。それは私の最終年度のプロジェクトは親切に私を助けているout.Hereは私のコードです:は、C#を使用してPythonプログラムを実行する方法はありますか?

テスト:

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); 
      } 
     } 
    } 
} 

テストスクリプトを呼び出すPythonスクリプトを実行します.py

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 
関連する問題