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

发布于 2021-02-02 23:21:25

如果我执行以下操作:

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。我该如何解决?

关注者
0
被浏览
87
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    Popen.communicate() 说明文件:

    请注意,如果要将数据发送到进程的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
    

    警告使用communication()而不是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
    # ->
    

    在当前的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
    # -> 
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看