Python - 如何将字符串传递给subprocess.Popen(使用stdin参数)?

Dar*_*zer 263 python stdin subprocess

如果我执行以下操作:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
Run Code Online (Sandbox Code Playgroud)

我明白了:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
Run Code Online (Sandbox Code Playgroud)

显然,一个cStringIO.StringIO对象不能足够接近文件duck以适应subprocess.Popen.我该如何解决这个问题?

jfs*_*jfs 310

Popen.communicate() 文档:

请注意,如果要将数据发送到进程的stdin,则需要使用stdin = PIPE创建Popen对象.同样,要在结果元组中获取除None之外的任何内容,您还需要提供stdout = PIPE和/或stderr = PIPE.

替换os.popen*

    pipe = os.popen(cmd, 'w', bufsize)
    # ==>
    pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
Run Code Online (Sandbox Code Playgroud)

警告使用通信(),而不是stdin.write(),stdout.read()或stderr.read(),以避免死锁由于任何其他OS管道缓冲区填满和阻断子进程.

所以你的例子可以写成如下:

from subprocess import Popen, PIPE, STDOUT

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
Run Code Online (Sandbox Code Playgroud)

在当前的Python 3版本中,您可以使用subprocess.run,将输入作为字符串传递给外部命令并获取其退出状态,并在一次调用中将其输出作为字符串返回:

#!/usr/bin/env python3
from subprocess import run, PIPE

p = run(['grep', 'f'], stdout=PIPE,
        input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# -> 
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的解决方案.特别是,如果执行此操作,则无法异步处理p.stdout.readline输出,因为您必须等待整个stdout到达.它也是内存效率低下的. (11认同)
  • @Nick T:"*更好*"取决于背景.牛顿定律适用于它们适用的领域,但你需要特殊的相对论来设计GPS.请参阅[python中的subprocess.PIPE上的非阻塞读取](http://stackoverflow.com/q/375427). (11认同)
  • 但请注意[通信]的注释(http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate):"如果数据大小很大或无限制,请不要使用此方法" (9认同)
  • @OTZ什么是更好的解决方案? (6认同)
  • 我错过了那个警告.我很高兴我问(即使我认为我有答案). (3认同)
  • 您需要 python 3.6 才能将“input”参数与“subprocess.run()”一起使用。如果你这样做,旧版本的 python3 就可以工作: `p = run(['grep', 'f'], stdout=PIPE, input=some_string.encode('ascii'))` (2认同)

Dar*_*zer 45

我想出了这个解决方法:

>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
Run Code Online (Sandbox Code Playgroud)

还有更好的吗?

  • @Moe:不建议使用`stdin.write()`用法,应该使用`p.communicate()`.看我的回答. (24认同)
  • 根据子进程文档:警告 - 使用communic()而不是.stdin.write,.stdout.read或.stderr.read来避免由于任何其他OS管道缓冲区填满和阻止子进程而导致的死锁. (10认同)
  • 这不是一种解决方法 - 这是正确的方法! (9认同)
  • 如果您确信您的 stdout/err 永远不会填满(例如,它将转到一个文件,或者另一个线程正在吃它)并且您拥有无限量的数据,我认为这是一个很好的方法发送到标准输入。 (2认同)

Gra*_*sen 24

我有点惊讶没有人建议创建一个管道,在我看来,这是将字符串传递给子进程的stdin最简单的方法:

read, write = os.pipe()
os.write(write, "stdin input here")
os.close(write)

subprocess.check_call(['your-command'], stdin=read)
Run Code Online (Sandbox Code Playgroud)

  • `os`和`subprocess`文档都同意你应该优先选择后者而不是前者.这是一种传统的解决方案,具有(略微简洁)标准替代品; 接受的答案引用了相关文件. (2认同)
  • -1:它导致死锁,它可能会丢失数据.子功能模块已经提供了此功能.使用它而不是重新实现它(尝试写一个大于OS管道缓冲区的值) (2认同)
  • @tripleee subprocess 模块中管道的实现是可笑的糟糕,并且无法控制。你甚至无法获得有关内置缓冲区大小的信息,更不用说,你无法告诉它管道的读写端是什么,也无法更改内置缓冲区。简而言之:子进程管道是垃圾。不要使用它们。 (2认同)

Fli*_*imm 20

如果您使用的是Python 3.4或更高版本,那么这是一个美丽的解决方案.使用input参数而不是stdin参数,它接受一个bytes参数:

output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)
Run Code Online (Sandbox Code Playgroud)

  • @vidstige你是对的,这很奇怪.我会考虑将其归为Python错误,我没有看到为什么`check_output`应该有一个`input`参数,而不是`call`. (3认同)
  • 这是 Python 3.4+ 的最佳答案(在 Python 3.6 中使用它)。它确实不适用于 `check_call`,但它适用于 `run`。只要您根据文档传递编码参数,它也适用于 input=string 。 (2认同)

qed*_*qed 14

我正在使用python3并发现你需要对你的字符串进行编码才能将它传递给stdin:

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(input='one\ntwo\nthree\nfour\nfive\nsix\n'.encode())
print(out)
Run Code Online (Sandbox Code Playgroud)

  • 你不需要对输入进行编码,它只需要一个类似字节的对象(例如`b'something').它也会以字节的形式返回err和out.如果你想避免这种情况,可以将`universal_newlines = True`传递给`Popen`.然后它将接受输入为str并将返回err/out作为str. (4认同)
  • 但要注意,`universal_newlines = True`也会转换你的新行以匹配你的系统 (2认同)

Dan*_*ski 13

"显然cStringIO.StringIO对象并不足够接近文件duck以适应subprocess.Popen"

:-)

恐怕不是.管道是一个低级操作系统概念,因此它绝对需要一个由操作系统级文件描述符表示的文件对象.你的解决方法是正确的.


小智 7

from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()
Run Code Online (Sandbox Code Playgroud)

  • fyi,tempfile.SpooledTemporaryFile .__ doc__说:临时文件包装器,专门用于在超过特定大小或需要fileno时从StringIO切换到实际文件. (3认同)

小智 6

"""
Ex: Dialog (2-way) with a Popen()
"""

p = subprocess.Popen('Your Command Here',
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 stdin=PIPE,
                 shell=True,
                 bufsize=0)
p.stdin.write('START\n')
out = p.stdout.readline()
while out:
  line = out
  line = line.rstrip("\n")

  if "WHATEVER1" in line:
      pr = 1
      p.stdin.write('DO 1\n')
      out = p.stdout.readline()
      continue

  if "WHATEVER2" in line:
      pr = 2
      p.stdin.write('DO 2\n')
      out = p.stdout.readline()
      continue
"""
..........
"""

out = p.stdout.readline()

p.wait()
Run Code Online (Sandbox Code Playgroud)

  • 因为`shell = True`是如此常用而没有充分理由,这是一个很受欢迎的问题,让我指出有很多情况下`Popen(['cmd','with','args'] ``肯定比`Popen(带有args'的cmd,shell = True)更好,并且让shell将命令和参数分解为令牌,但不提供任何有用的东西,同时增加了大量的复杂性,因此也会攻击表面. (4认同)

Lor*_*ton 5

请注意,Popen.communicate(input=s)如果s太大,可能会给你带来麻烦,因为显然父进程会分配子子进程之前缓冲它,这意味着它需要"两倍于"使用内存(至少根据"引擎盖下"的解释和链接文档在这里找到).在我的特定情况下,s是一个首先完全展开的生成器,然后才写入,stdin因此父进程在生成子进程之前是巨大的,并且没有留下任何内存来分叉它:

File "/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py", line 1130, in _execute_child self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory


Bor*_*ris 5

在 Python 3.7+ 上执行以下操作:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)
Run Code Online (Sandbox Code Playgroud)

并且您可能想要添加capture_output=True以获取以字符串形式运行命令的输出。

在旧版本的 Python 上,替换text=Trueuniversal_newlines=True

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)
Run Code Online (Sandbox Code Playgroud)