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

问题描述 投票:264回答:11

如果执行以下操作:

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

我得到:

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'

显然,cStringIO.StringIO对象的震级离文件鸭子不足以适应subprocess.Popen。我该如何解决?

python subprocess stdin
11个回答
310
投票

Popen.communicate()文档:

注意,如果要将数据发送到流程的标准输入,您需要使用创建Popen对象stdin = PIPE。同样,得到任何东西除了结果元组中的None以外,您需要提供stdout = PIPE和/或stderr = PIPE也是。

替换os.popen *

Popen.communicate()

警告使用communication()而不是stdin.write(),stdout.read()或stderr.read()避免死锁到任何其他OS管道缓冲区填满并阻止孩子过程。

因此您的示例可以编写如下:

    pipe = os.popen(cmd, 'w', bufsize)
    # ==>
    pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin

在当前的Python 3版本上,您可以使用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 # -> 将输入作为字符串传递给外部命令,并获取其退出状态,并在一次调用中将其输出作为字符串返回:

subprocess.run

2
投票
stdin

0
投票

在Python 3.7+上执行此操作:

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

并且您可能想要添加p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) p.stdin.write('one\n') time.sleep(0.5) p.stdin.write('two\n') time.sleep(0.5) p.stdin.write('three\n') time.sleep(0.5) testresult = p.communicate()[0] time.sleep(0.5) print(testresult) 以获取将命令作为字符串运行的输出。

在旧版本的Python上,将my_data = "whatever you want\nshould match this f" subprocess.run(["grep", "f"], text=True, input=my_data) 替换为capture_output=True

text=True

44
投票

我想出了解决方法:

subprocess.run

有更好的一个吗?


23
投票

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

#!/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
# -> 

19
投票

如果您使用的是Python 3.4或更高版本,这是一个美丽的解决方案。使用>>> 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() 参数代替read, write = os.pipe() os.write(write, "stdin input here") os.close(write) subprocess.check_call(['your-command'], stdin=read) 参数,该参数接受一个字节参数:

input

13
投票

我正在使用python3,发现您需要先对字符串进行编码,然后才能将其传递到stdin:

stdin

12
投票

“显然,cStringIO.StringIO对象没有足够接近库文件的鸭子以适应subprocess.Popen”

:-)

恐怕不是。管道是低级OS概念,因此绝对需要由OS级文件描述符表示的文件对象。您的解决方法是正确的。


6
投票
output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

5
投票
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)

4
投票

请注意,如果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() 太大,""" 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() 可能会给您带来麻烦,因为显然父进程会对其进行缓冲之前分叉子子进程,这意味着此时该子进程需要“两倍多”的已用内存(至少根据“内幕”说明和找到的链接文档Popen.communicate(input=s))。在我的特殊情况下,s是一个生成器,该生成器首先被完全扩展,然后才写入here,因此在生成子对象之前,父进程非常庞大,并且没有剩余的内存来存储它:

s

© www.soinside.com 2019 - 2024. All rights reserved.