我如何传递一个字符串到子进程。Popen(使用stdin参数)?

如果我这样做:

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。我怎么解决这个问题呢?

401753 次浏览

我想出了一个变通办法:

>>> 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()

还有更好的吗?

显然是cStringIO。StringIO对象的嘎嘎声不够接近 适合子进程的文件鸭。Popen < / p >

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

Popen.communicate()文档:

注意,如果你想发送数据到 这个过程是标准的,你需要 创建Popen对象 stdin =管。同样,要得到任何东西 除了结果元组中的None, 你需要给stdout=PIPE和/或 stderr =管。< / p >

取代os.popen *

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

警告使用communication()而不是 Stdin.write (), stdout.read()或 Stderr.read()避免死锁 到任何其他操作系统管道缓冲区 填充和阻塞孩子 过程。< / p >

所以你的例子可以写成这样:

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

在Python 3.5+ (encoding为3.6+)上,你可以使用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
# ->
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)
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()
注意,如果__abc1太大,__abc0可能会给你带来麻烦,因为显然父进程会缓冲它之前派生子进程,这意味着它需要“两倍”的使用内存(至少根据“引子”的解释和链接文档找到在这里)。在我的特殊情况下,__abc1是一个生成器,它首先被完全扩展,然后才被写入__abc3,所以在子进程被生成之前,父进程非常庞大, 并且没有剩余的内存来fork它:

文件"/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py",第1130行,在_execute_child中 自我。Pid = os.fork() OSError: [Errno 12]不能分配内存

我使用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)

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

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


subprocess.check_call(['your-command'], stdin=read)

如果您使用的是Python 3.4或更高版本,那么有一个很好的解决方案。使用input实参代替stdin实参,后者接受一个bytes实参:

output_bytes = subprocess.check_output(
["sed", "s/foo/bar/"],
input=b"foo",
)

这适用于check_outputrun,但由于某些原因不适用于callcheck_call

在Python 3.7+中,你还可以添加text=True,使check_output接受字符串作为输入并返回字符串(而不是bytes):

output_string = subprocess.check_output(
["sed", "s/foo/bar/"],
input="foo",
text=True,
)

在Python 3.7+上这样做:

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

你可能会想要添加capture_output=True来获得运行命令的输出作为字符串。

在较旧版本的Python中,将text=True替换为universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

这对于grep来说有点过分了,但通过我的旅程,我已经了解了Linux命令expect和python库pexpect

  • expect:与交互程序对话
  • pexpect:用于生成子应用程序的Python模块;控制他们;并在他们的输出中响应预期的模式。
import pexpect
child = pexpect.spawn('grep f', timeout=10)
child.sendline('text to match')
print(child.before)

使用ftp这样的交互式shell应用程序对pexpect来说很简单

import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('ls /pub/OpenBSD/')
child.expect ('ftp> ')
print child.before   # Print the result of the ls command.
child.interact()     # Give control of the child to the user.