passing data to subprocess.check_output

后端 未结 3 1556
醉酒成梦
醉酒成梦 2020-12-15 16:25

I want to invoke a script, piping the contents of a string to its stdin and retrieving its stdout.

I don\'t want to touch the real filesystem so I can\'t create real

3条回答
  •  借酒劲吻你
    2020-12-15 16:59

    In Python 3.4 and newer, you can use the input keyword parameter to send input via STDIN when using subprocess.check_output()

    Quoting from the standard library documentation for subprocess.check_output():

    The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well.

    Example:

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

提交回复
热议问题