如何使用 cmd.exe 从 C# 应用程序运行 Python 代码
本文关键字:应用程序 运行 Python 代码 何使用 cmd exe | 更新日期: 2023-09-27 18:33:13
我有一个应用程序,我正在尝试从 C# 应用程序运行 python。 我尝试创建 Python 运行时环境并运行代码,但是当我的 Python 代码从另一个 Python 文件导入一些模块时,它会抛出异常(导入异常)。 我尝试了以下代码:
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile(@"file path");
test.Simple();
Console.Read();
我有另一个通过cmd提示符运行它的想法,但我不知道该怎么做。 我想打开 cmd.exe 并执行 python 文件,我希望它允许用户在 C# 应用程序中输入文件名,然后单击运行按钮时,代码通过 cmd 执行.exe输出再次显示在 C# 应用程序中。也欢迎任何其他建议。
这将完成这项工作:以下示例运行运行 TCL 脚本的 cmd(我已安装在我的计算机上的那个 wat 你只需要替换命令来运行 Python 并添加你的脚本文件。注意脚本文件名后面的" & exit" - 这使得cmd在脚本退出后退出。
string fileName = "C:''Tcl''example''hello.tcl";
Process p = new Process();
p.StartInfo = new ProcessStartInfo("cmd", "/K tclsh " + fileName + " & exit")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
[更新]
在 Python 安装和测试之后,这将是使用 cmd 运行 python 脚本的代码:
string fileName = @"C:'Python27'example'hello_world.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo("cmd", "/K " + fileName + " & exit")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
您也可以在没有CMD过程的情况下执行相同的操作:
string fileName = @"C:'Python27'example'hello_world.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:'Python27'python.exe", fileName )
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
我目前无法亲自测试它,但我发现有些人在他们的代码中使用Python.CreateEngine()
,例如:
Microsoft.Scripting.Hosting.ScriptEngine engine =
IronPython.Hosting.Python.CreateEngine();
这句话取自这个SO问题。
您还可以使用 python 代码的示例类查看本文。它还使用Python.CreateEngine()
.
我尝试了以下代码,它似乎解决了我的问题:
Process p = new Process();
string cmd = @"python filepath & exit";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.RedirectStandardInput = true;
p.Start();
StreamWriter myStreamWriter = p.StandardInput;
myStreamWriter.WriteLine(cmd.ToString());
myStreamWriter.Close();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.ReadLine();