[英]how to run a python code using cmd.exe from a C# application?
我有一個應用程序,我正在嘗試從ac#應用程序運行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#應用程序中再次顯示輸出。 也歡迎任何其他建議。
這樣就可以了:下面的示例運行cmd,該cmd運行TCL腳本(我已經安裝在我的計算機上的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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.