python stdin.write_如何写入Python子进程的stdin?

本文详细讲解了如何在Python中使用subprocess模块进行子进程通信,特别关注了stdin、stdout的处理,并通过实例演示了如何通过管道传递数据,如grep和wc的配合。重点提到了Python 3.4中字符串编码的注意事项。
摘要由CSDN通过智能技术生成

为了澄清一些问题:

由于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中直接添加数据。

希望能帮上忙。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值