代码应该运行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()
没有的缓冲区执行某些操作。
答案 0 :(得分:2)
抱歉比我预期的要长一点。这是一个诡异的怪(即你不会在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();
}
}
}