c# - 如何等待操作完成?

标签 c# python cmd

我有 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/

相关文章:

c# - 如何结合自定义序列化程序使用/启用 LINQ? (MONGODB C#)

c# - 0MQ windows GUI 最佳实践

c# - 如何动态检查数组中的索引是否存在?

c# - 无法通过 C# 访问 C++/CLI 重载运算符

c++ - 我正在尝试使用 C++ 通过命令行打开 gnuplot 并编译图形

javascript - 控制台写入速度会影响程序执行速度吗

python - 在 Splinter 中获取 href 值?

python - 用Python抓取具有多个输入的网页

python - 如何使 parsedatetime 忽略日期后面的冒号?

windows - 将 jpg 文件递归搜索、复制和重命名为父文件夹名称