直接在子进程库中的process.communicate()中输入

时间:2017-01-05 07:53:01

标签: python python-3.x subprocess

我想同时使用多行输入命令' cat - '并在' pwd'中输入单行。

为此我试图直接在process.communicate()中获取输入,我收到管道错误。在论证中我应该取代什么?

command = 'cat -'
stdout_value=''

process = subprocess.Popen(shlex.split(command),
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    shell=True)
while True:
    if process.poll() is not None:
    break    
    stdout_value = stdout_value + process.communicate(process.stdin)[0]

print(repr(stdout_value))

此代码出错:

Traceback (most recent call last):
  File "try.py", line 67, in <module>
    stdout_value = stdout_value + process.communicate(process.stdin)[0]
  File "/usr/lib64/python3.5/subprocess.py", line 1068, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "/usr/lib64/python3.5/subprocess.py", line 1687, in _communicate
    input_view = memoryview(self._input)
TypeError: memoryview: a bytes-like object is required, not '_io.BufferedWriter'
[vibhcool@localhost try]$ Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

1 个答案:

答案 0 :(得分:0)

process.communicate()期望您拥有encoded()字符串的字符串,并将您必须decode()的字节返回给字符串。

您使用的不是字符串process.stdin。它甚至没有方法read()来执行process.communicate(process.stdin.read())(除了使用process.stdin使用相同的process没有任何意义)。它可能是process.communicate(other_process.stdout.read())(如果你有其他过程)

工作示例 - 我将带有数字的文本发送到命令sort,并返回带有已排序数字的文本。

input:  3\n2\n5\n-1
output: -1\n2\n3\n5\n

代码

import subprocess
import shlex

command = 'sort'

process = subprocess.Popen(shlex.split(command),
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    shell=True)

stdout_value = ''

while True:
    if process.poll() is not None:
        break
    result = process.communicate("3\n2\n5\n-1".encode('utf-8'))[0]
    stdout_value += result.decode('utf-8')

print(repr(stdout_value))