我有 C# 代码,其中包括 Python 代码,其中它通过 C# 中的 CMD 代码运行。当Python代码运行时,操作完成,创建一个JSON文件,然后用C#打开它。在这种情况下,C# 代码如何等待检查 Python 的输出 (data.json
) 是否已创建,并且在创建输出时,允许其余的 C# 代码运行:
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("F:\\");
process.StandardInput.WriteLine("cd F:\\Path");
process.StandardInput.WriteLine("python Python_Code.py");
process.StandardInput.Flush();
process.StandardInput.Close();
process.WaitForExit();
然后,将检索使用Python生成的数据:
string Output_Python = File.ReadAllText(@"Data.json");
JavaScriptSerializer Ser = new JavaScriptSerializer();
Predicted Output = Ser.Deserialize<Predicted>(Output_Python);
最佳答案
您不需要通过cmd.exe。 Python解释器本身是一个可执行文件;也就是说,可以直接启动并执行。 Python 解释器的参数(如要执行的脚本的路径+名称)和所需的工作目录可以通过适当的 Process.StartInfo properties 设置。 :
Process process = new Process();
process.StartInfo.FileName = "python.exe";
process.StartInfo.Arguments = "Python_Code.py";
process.StartInfo.WorkingDirectory = @"F:\Path";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
现在你只需要等待Python解释器退出(这意味着它完成了python脚本的执行)
process.WaitForExit();
Python进程退出后,只需检查json文件是否存在/已写入:
if (System.IO.File.Exists(pathToJsonFile))
{
... do stuff with json file ...
}
else
{
... json file does not exist, something went wrong...
}
<小时/>
旁注:我在此处的代码示例中保留了 process.StartInfo.RedirectStandardOutput = true;
,因为我不知道您的程序实际上会做什么。但是,除非您的程序想要处理通常出现在控制台窗口中的脚本的输出,否则不需要将 RedirectStandardOutput 设置为 true。
关于c# - 如何等待操作完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54855527/