在Python中如何将字符串传递给可执行文件stdin?

KFL*_*KFL 1 python windows subprocess pipe

在Windows上我有一个从stdin读取的程序(prog.exe).在python中我想管道一个字符串作为其stdin的输入.怎么做?

就像是:

subprocess.check_output("echo {0} | myprog.exe".format(mystring)) 
Run Code Online (Sandbox Code Playgroud)

或者(使args成为一个列表)

subprocess.check_output("echo {0} | myprog.exe".format(mystring).split())
Run Code Online (Sandbox Code Playgroud)

似乎不起作用.它给了我:

WindowsError: [Error 2] The system cannot find the file specified
Run Code Online (Sandbox Code Playgroud)

我还尝试使用StringIO的"stdin"关键字arg(这是一个类似文件的对象)

subprocess.check_output(["myprog.exe"], stdin=StringIO(mystring))
Run Code Online (Sandbox Code Playgroud)

仍然没有运气 - check_output不适用于StringIO.

wim*_*wim 5

你应该使用Popen communicate方法(docs).

proc = subprocess.Popen(["myprog.exe"], stdin=subprocess.PIPE)
stdout, stderr = proc.communicate('my input')
Run Code Online (Sandbox Code Playgroud)