代码之家  ›  专栏  ›  技术社区  ›  hcs42

如何在python 2中将字符串传递给subprocess.popen?[复制品]

  •  3
  • hcs42  · 技术社区  · 16 年前

    我想从python(2.4/2.5/2.6)运行一个进程,使用 Popen 和我 希望给它一个字符串作为标准输入。

    我将编写一个示例,其中流程执行“head-n 1”输入。

    以下是可行的,但我希望以更好的方式解决它,而不使用 echo :

    >>> from subprocess import *
    >>> p1 = Popen(["echo", "first line\nsecond line"], stdout=PIPE)
    >>> Popen(["head", "-n", "1"], stdin=p1.stdout)
    first line
    

    我试着用 StringIO 但它不起作用:

    >>> from StringIO import StringIO
    >>> Popen(["head", "-n", "1"], stdin=StringIO("first line\nsecond line"))
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
      File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
        (p2cread, p2cwrite,
      File "/usr/lib/python2.4/subprocess.py", line 830, in _get_handles
        p2cread = stdin.fileno()
    AttributeError: StringIO instance has no attribute 'fileno'
    

    我想我可以做一个临时文件,在那里写字符串——但这也不是很好。

    2 回复  |  直到 9 年前
        1
  •  8
  •   Nadia Alramli    16 年前

    你试过把你的绳子给 communicate 作为一根绳子?

    Popen.communicate(input=my_input)
    

    工作原理如下:

    p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)
    p.communicate('first\nsecond')
    

    输出:

    first
    

    刚开始尝试时,我忘记将stdin设置为subprocess.pipe。

        2
  •  5
  •   Nicolas Dumazet    16 年前

    使用 os.pipe 以下内容:

    >>> from subprocess import Popen
    >>> import os, sys
    >>> read, write = os.pipe()
    >>> p = Popen(["head", "-n", "1"], stdin=read, stdout=sys.stdout)
    >>> byteswritten = os.write(write, "foo bar\n")
    foo bar
    >>>