如何等待操作完成?

时间:2019-02-24 19:13:02

标签: 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);

3 个答案:

答案 0 :(得分:1)

您不需要通过cmd.exe。 Python解释器本身是可执行文件。换句话说,它可以直接启动和执行。可以通过适当的Process.StartInfo properties设置Python解释器的参数(例如要执行的脚本的路径+名称)和所需的工作目录:

Service Workers

现在您只需要等待Python解释器退出(这意味着它已完成执行python脚本)

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进程退出后,只需检查json文件是否存在/是否已被写入:

process.WaitForExit();

旁注:由于我不知道您的程序真正会做什么,因此我在此处的代码示例中保留了if (System.IO.File.Exists(pathToJsonFile)) { ... do stuff with json file ... } else { ... json file does not exist, something went wrong... } 。但是,除非您的程序要处理通常出现在控制台窗口中的脚本的输出,否则不必将 RedirectStandardOutput 设置为 true

答案 1 :(得分:0)

您应该看看FileSystemWatcher类。文档here

然后您可以执行以下操作:

using (FileSystemWatcher watcher = new FileSystemWatcher())
{
    watcher.Path = YourDirectory;
    // Watch for changes in LastWrite time
    watcher.NotifyFilter = NotifyFilters.LastWrite;

    // Watch for the wanted file
    watcher.Filter = "data.json";

    // Add event handlers.
    watcher.Created += WhateverYouWantToDo;
}

答案 2 :(得分:0)

您可以检查文件data.json是否已完成写入其输出文件夹(来自this answer的代码):

private bool IsFileLocked(FileInfo file) 
{ 
   FileStream stream = null; 
   try 
  { 
    stream = file.Open(FileMode.Open,    FileAccess.ReadWrite, FileShare.None); 
  } 
  catch (IOException)
  { 
//the file is unavailable because it is: 
//still being written to 
//or being processed by another thread 
//or does not exist (has already been processed) 
    return true; 
  }
  finally 
  { 
    if (stream != null) stream.Close(); 
  } 
//file is not locked return 
return false; 
}