我正在尝试使用 subprocess.popen() io.BytesIO() bytetream传递到单独的程序中,但我不知道这是怎么做或是否完全可能。文档和示例都是关于文本和换行符的。

当我鞭打像这样的东西:

import io
from subprocess import *

stream = io.BytesIO()
someStreamCreatingProcess(stream)

command = ['somecommand', 'some', 'arguments']
process = Popen(command, stdin=PIPE)
process.communicate(input=stream)

我懂了
Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    procOut         = process.communicate(input=stream)
  File "/usr/lib/python2.7/subprocess.py", line 754, in communicate
    return self._communicate(input)
  File "/usr/lib/python2.7/subprocess.py", line 1322, in _communicate
    stdout, stderr = self._communicate_with_poll(input)
  File "/usr/lib/python2.7/subprocess.py", line 1384, in _communicate_with_poll
    chunk = input[input_offset : input_offset + _PIPE_BUF]
TypeError: '_io.BytesIO' object has no attribute '__getitem__'

我认为 popen()仅适用于文本。我错了吗?
有其他方法可以做到这一点吗?

最佳答案

作为@falsetru said,您不能直接流式传输BytesIO()对象;您需要先从中获取一个字节串。这意味着在调用stream传递给stream.getvalue()之前,所有内容都应该已经写入process.communicate()

如果要流式传输而不是一次提供所有输入,则可以删除BytesIO()对象并直接写入管道:

from subprocess import Popen, PIPE

process = Popen(['command', 'arg1'], stdin=PIPE, bufsize=-1)
someStreamCreatingProcess(stream=process.stdin) # many `stream.write()` inside
process.stdin.close() # done (no more input)
process.wait()
someStreamCreatingProcess()在完成写入流之前不应该返回。如果立即返回,则应在将来的某个时间调用stream.close()(在您的代码中删除process.stdin.close()):
from subprocess import Popen, PIPE

process = Popen(['command', 'arg1'], stdin=PIPE, bufsize=-1)
someStreamCreatingProcess(stream=process.stdin) # many `stream.write()` inside
process.wait() # stream.close() is called in `someStreamCreatingProcess`

关于python - 我可以将io.BytesIO()流传输到Python中的subprocess.popen()吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20321116/

10-12 16:48