c# - 在输入流关闭之前无法执行进程

标签 c#

该代码应该运行 python 并接受来自 StreamWriter 的 python 命令。但仅关闭 StreamWriter 会导致代码执行 - 这并不好:

private Process p = new Process();
p.StartInfo = new ProcessStartInfo()
{
    FileName = "python",
    UseShellExecute = false,
    RedirectStandardInput = true,
    RedirectStandardOutput = false
};
p.Start();

//new Task(WriteInputTask).Start();

private StreamWriter sw = p.StandardInput;
sw.AutoFlush = true; //does nothing
sw.Write("print('Printing from python')" + Environment.NewLine);
sw.Flush(); //does nothing
sw.Close(); //NOW console shows "Printing from python"

我不想每次要发出新命令时都必须重新启动 python 并重新导入所有内容(尤其是需要半分钟才能导入的 arcpy)。 Close() 对缓冲区做了一些 Flush() 没有做的事情。

最佳答案

抱歉比我预期的要长一点。这是 python 的一个奇怪之处(即你在 cmd 中看不到这种行为)。您需要在启动时将“-i”开关添加到 python。这是一个完整的工作示例。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace stackoverflow1 {
class Program {

    static void Main(string[] args) {
        var exe = "python";
        var arguments = "-i";

        Process p = new Process();
        p.StartInfo = new ProcessStartInfo() {
            FileName = exe,
            Arguments = arguments,
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            StandardOutputEncoding = Encoding.UTF8,
            StandardErrorEncoding = Encoding.UTF8,
            CreateNoWindow = false,
        };

        p.OutputDataReceived += new DataReceivedEventHandler(
            delegate (object sendingProcess, DataReceivedEventArgs outLine) {
                Console.WriteLine("{0}: {1}", exe, outLine.Data);
                });

        p.ErrorDataReceived += new DataReceivedEventHandler(
            delegate (object sendingProcess, DataReceivedEventArgs errLine) {
                Console.WriteLine("Error: " + errLine.Data);
                });

        p.Start();
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();

        StreamWriter sw = p.StandardInput;
        sw.AutoFlush = true; //does nothing

        if (exe == "cmd") {
            sw.WriteLine("echo hello");
            sw.WriteLine("echo 2+2");
            sw.WriteLine("echo Goodbye");
            }
        else { // assume python
            sw.WriteLine("print('Hello')");
            sw.WriteLine("2+2");
            sw.WriteLine("print('Printing from python')");
            sw.WriteLine("print('Goodbye')");
            }
        sw.Flush();

        System.Threading.Thread.Sleep(200);
        Console.WriteLine("Closing");
        sw.Close();

        Console.ReadKey();
        }
   }
}

关于c# - 在输入流关闭之前无法执行进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29710625/

相关文章:

c# - 计算有多少种方法可以将三个数字相加使它们等于 1000

c# - 列表转二维数组

c# - Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential 不采用 2 个参数?

c# - 如何获取特定的套接字并关闭它

c# - 为什么 if 语句中的这个字符串初始化会阻止我打印?

c# - 减少文件操作的内存占用

c# - 检查 WebAPI 在 C# Code Behind 中是否可用的简单、最佳方法

C#/XNA - 将对象加载到内存 - 它是如何工作的?

c# - 领域驱动设计应用服务

c# - 在 LinQ 表达式树中声明变量