簡體   English   中英

從C#表單應用程序執行python 3代碼

[英]Execute python 3 code from c# forms application

作為一個學校項目,我的班級使用python 3創建了一種簡單的編程語言。現在,我們在c#中創建了一個簡單的思想,該思想應在新的控制台窗口中執行python腳本。 我想知道什么是最有效的方法。 (我應該使用參數執行它)

您可以使用ProcessStartInfo

int parameter1 = 10;
int parameter2  = 5
Process p = new Process(); // create process to run the python program
p.StartInfo.FileName = "python.exe"; //Python.exe location
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false; // ensures you can read stdout
p.StartInfo.Arguments = "c:\\src\\yourpythonscript.py "+parameter1 +" "+parameter2; // start the python program with two parameters
p.Start(); // start the process (the python program)
StreamReader s = p.StandardOutput;
String output = s.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();

有兩種方法可以運行python腳本:

  1. 一種運行python腳本的方法是運行python.exe文件:
    使用ProcessStartInfo運行python.exe文件,並在其上傳遞python腳本。

私人空隙run_cmd(string cmd,string args){
ProcessStartInfo start =新的ProcessStartInfo();

  start.FileName = "my/full/path/to/python.exe"; start.Arguments = string.Format("{0} {1}", cmd, args); start.UseShellExecute = false; start.RedirectStandardOutput = true; using(Process process = Process.Start(start)) { using(StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } } 
  1. 另一種方法是使用IronPython並直接執行python腳本文件。

使用IronPython.Hosting;
使用Microsoft.Scripting.Hosting;

 private static void doPython() { ScriptEngine engine = Python.CreateEngine(); engine.ExecuteFile(@"test.py"); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM