【发布时间】:2015-09-19 05:12:07
【问题描述】:
我想从 Windows 中的外部进程将数据写入现有进程的 stdin。
我在 Linux 上发现了类似的问题,但我想知道如何在 Windows 中做同样的事情。
How to write data to existing process's STDIN from external process?
How do you stream data into the STDIN of a program from different local/remote processes in Python?
https://serverfault.com/questions/443297/write-to-stdin-of-a-running-process-using-pipe
我尝试使用此代码,但出现错误。我还尝试运行该程序,使用此代码向该程序发送stdin,但再次出错。
在 CMD 中:
type my_input_string | app.exe -start
my_input_string | app.exe -start
app.exe -start < pas.txt
在python中:
p = subprocess.Popen('"C:\app.exe" -start', stdin=subprocess.PIPE, universal_newlines=True, shell=True)
grep_stdout = p.communicate(input='my_input_string')[0]
我得到的错误是:
ReadConsole()失败:句柄无效。
在 C# 中:
try
{
var startInfo = new ProcessStartInfo();
startInfo.RedirectStandardInput = true;
startInfo.FileName = textBox1.Text;
startInfo.Arguments = textBox2.Text;
startInfo.UseShellExecute = false;
var process = new Process();
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(1000);
var streamWriter = process.StandardInput;
streamWriter.WriteLine("1");
}
catch (Exception ex)
{
textBox4.Text = ex.Message+"\r\n"+ex.Source;
}
在 C# 中,使用上面的代码,App.exe(启动另一个进程的命令行应用程序)崩溃,但在 C# 应用程序中我没有任何异常。我认为这是因为UseShellExecute = false。
如果我在运行 C# 应用程序时选择“不要在后台运行应用程序”,我可以找到该进程并使用sendkeys 向它发送my_input_string,但这不是一个好主意,因为用户在运行 GUI 时可以看到命令行。
我怎样才能发送stdin,只使用 CMD、python 脚本或 C#,没有任何错误?
【问题讨论】:
-
呃,对不起,但我不知道……谁在给谁写信? Python 到 C#? C# 到 Python?你想要一般情况吗?
-
@NightShadeQueen 我想要一种从 python 或 C# 写入标准输入的方法,我尝试在 python 中编写脚本并从 C# 运行。
-
查看我的this answer 中的
errorwindow.py模块,因为它完成了我认为您正在尝试做的事情。主要区别在于,一个进程的输出通过打印(或将其写入stderr)发送到另一个进程。在我的other answer 中,同样的模块也用于完成与相关问题类似的事情。
标签: c# python process cmd stdin