36

我想调用一个脚本,将字符串的内容传送到它的标准输入并检索它的标准输出。

我不想接触真正的文件系统,所以我不能为它创建真正的临时文件。

使用subprocess.check_output我可以获得脚本所写的任何内容;我怎样才能将输入字符串输入到它的标准输入中呢?

subprocess.check_output([script_name,"-"],stdin="this is some input")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.7/subprocess.py", line 1043, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'str' object has no attribute 'fileno'
4

3 回答 3

36

使用Popen.communicate而不是subprocess.check_output.

from subprocess import Popen, PIPE

p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate("this is some input")
于 2012-04-11T09:58:08.170 回答
26

在 Python 3.4 及更高版本中,您可以在使用时使用input关键字参数通过 STDIN 发送输入subprocess.check_output()

引用标准库文档subprocess.check_output()

输入参数被传递给Popen.communicate()子进程的标准输入。如果使用它必须是一个字节序列,或者一个字符串 if universal_newlines=True。使用时,内部Popen对象会自动创建stdin=PIPE,而stdin参数也可能不使用。

例子:

>>> subprocess.check_output(["sed", "-e", "s/foo/bar/"],
...                         input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
>>> 
>>> # To send and receive strings instead of bytes,
>>> # pass in universal_newlines=True
>>> subprocess.check_output(["sed", "-e", "s/foo/bar/"],
...                         universal_newlines=True,
...                         input="when in the course of fooman events\n")
'when in the course of barman events\n'
于 2014-08-28T05:54:25.433 回答
6

这是带有输入的 python 2.7 的 check_output 反向移植版本。

from subprocess import (PIPE, Popen, CalledProcessError)

def check_output_input(*popenargs, **kwargs):
    """Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    'ls: non_existent_file: No such file or directory\n'

    There is an additional optional argument, "input", allowing you to
    pass a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument, as
    it too will be used internally.  Example:

    >>> check_output(["sed", "-e", "s/foo/bar/"],
    ...              input=b"when in the course of fooman events\n")
    b'when in the course of barman events\n'

    If universal_newlines=True is passed, the return value will be a
    string rather than bytes.

    """
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    if 'input' in kwargs:
        if 'stdin' in kwargs:
            raise ValueError('stdin and input arguments may not both be used.')
        inputdata = kwargs['input']
        del kwargs['input']
        kwargs['stdin'] = PIPE
    else:
        inputdata = None
    process = Popen(*popenargs, stdout=PIPE, **kwargs)
    try:
        output, unused_err = process.communicate(inputdata)
    except:
        process.kill()
        process.wait()
        raise
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output
于 2015-05-05T23:25:23.620 回答