为了澄清一些问题:
由于jro有mentioned,正确的方法是使用subprocess.communicate。
然而,当使用带有input的subprocess.communicate来馈送stdin时,需要根据docs来启动带有stdin=subprocess.PIPE的子进程。Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
还有qed在注释中提到,对于Python 3.4,您需要对字符串进行编码,这意味着您需要将字节传递给input,而不是string。这并不完全正确。根据文档,如果流是以文本模式打开的,则输入应该是字符串(源是同一页)。If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.
因此,如果流不是在文本模式下显式打开的,则应该执行以下操作:import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]
我特意把上面的stderr值留作STDOUT示例。
也就是说,有时您可能需要另一个进程的输出,而不是从头开始构建它。假设您希望运行与echo -n 'CATCH\nme' | grep -i catch | wc -m等价的代码。这通常会返回“CATCH”中的数字字符和换行符,结果是6。回声的作用是将CATCH\nme数据馈送给grep。因此,我们可以用Python子进程链中的stdin作为变量将数据馈送给grep,然后将stdout作为管道传递给wc进程的stdin(同时,去掉多余的换行符):import subprocess
what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'
# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]
# Well the result includes an '\n' at the end,
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()
# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()
这与响应here有些不同,在响应中,您可以直接对两个进程进行管道传输,而无需在Python中直接添加数据。
希望能帮上忙。