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
请注意,如果要将数据发送到进程的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)
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)
还有更好的吗?
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)
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)
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)
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)
小智 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)
请注意,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
在 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=True为universal_newlines=True:
subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
289917 次 |
| 最近记录: |