2012-04-11 23 views
26

Quiero invocar un script, canalizando el contenido de una cadena a su stdin y recuperando su stdout.pasando datos a subprocess.check_output

No quiero tocar el sistema de archivos real, así que no puedo crear archivos temporales reales para él.

usando subprocess.check_output Puedo obtener lo que escriba el script; ¿cómo puedo obtener la cadena de entrada en su stdin sin embargo?

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

El 'stdin' arg para' check_output() 'debe ser un objeto de archivo, no una cadena. – jdi

+0

@jdi obviamente; Entonces, ¿cómo darle algo que grazna como un archivo pero no es un archivo? – Will

+0

Al elegir @larsmans responder :-) es mucho más fácil si no intentas usar en exceso la función de conveniencia 'check_output' y simplemente haces un Popen + comunico normal. De lo contrario, se espera que abra su propia tubería manualmente antes de la mano, y luego la pase a 'check_output (stdin)' y luego escriba en ella. – jdi

Respuesta

29

Uso Popen.communicate en lugar de 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") 
+0

Tuve que quitar el "-" para que funcione –

17

En Python 3.4 y posteriores, puede utilizar el parámetro palabra clave de entrada para enviar entrada a través de STDIN cuando se utiliza subprocess.check_output()

citando de the standard library documentation for subprocess.check_output():

El argumento de entrada es pasó a Popen.communicate() y, por lo tanto, a la entrada estándar del subproceso . Si se usa, debe ser una secuencia de bytes o una cadena si universal_newlines=True. Cuando se utiliza, el objeto Popen interno es creado automáticamente con stdin=PIPE, y el argumento stdin no se puede usar también.

Ejemplo:

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

Aquí hay una versión check_output portado para Python 2.7 con la entrada.

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