如果执行以下操作:
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。我该如何解决?
注意,如果要将数据发送到流程的标准输入,您需要使用创建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
stdin
在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
我想出了解决方法:
subprocess.run
有更好的一个吗?
令我惊讶的是,没有人建议创建管道,这在我看来是将字符串传递给子流程的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
# ->
如果您使用的是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
我正在使用python3,发现您需要先对字符串进行编码,然后才能将其传递到stdin:
stdin
“显然,cStringIO.StringIO对象的震级离文件鸭子还不足以适合subprocess.Popen”
:-)
恐怕不是。管道是低级OS概念,因此绝对需要由OS级文件描述符表示的文件对象。您的解决方法是正确的。
output = subprocess.check_output(
["sed", "s/foo/bar/"],
input=b"foo",
)
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)
请注意,如果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