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

标签 python subprocess 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。我该如何解决这个问题?

最佳答案

Popen.communicate()文档:

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Replacing os.popen*

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

Warning Use communicate() rather than stdin.write(), stdout.read() or stderr.read() to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

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

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

关于python - 如何将字符串传递给 subprocess.Popen(使用 stdin 参数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/163542/

相关文章:

python - 最Pythonic 的Tic-Tac-Toe 游戏板表示?

python - scikit-learn 中 predict_proba 的输出

python - 音乐在Python/Pygame中不起作用

python - 从 python 脚本调用别名命令

java - java中STDIN有哪些不同的方式

python - 用 pandas 中训练数据的平均值填充测试数据中的 nan 值

python - 扩展插值在 configparser 中不起作用

python - 使用 Python 子进程在 stdout 上捕获 C 程序的输出?希望吗?

bash - 此 shell 语法的机制 : ${1:-$(</dev/stdin)}

python - 如何在 Python 中将数据从不同的本地/远程进程流式传输到程序的 STDIN 中?