繁体   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