Search code examples
pythonsubprocessavprobe

How do you handle pipes and output in Python?


I'm attempting to execute this command within my python script:

avprobeCommand = "avprobe -of json -show_streams {0} | grep '\"duration\"' | sed -n 1p | sed 's/ //g'".format(hiOutput)
output = subprocess.check_output([avprobeCommand])

and I keep getting:

    Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 505, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/Users/jmakaila/Documents/Development/Present/Web/video_dev/present-live-transcoder/Transcoder.py", line 60, in transcode
    output = subprocess.check_output([avprobeCommand])
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1228, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

I've already tried splitting the args up, but I keep getting an error for the -of json -show_streams part, which, for the record, looked like this:

subprocess.check_output(["avprobe", "-of json", "-show_streams", "{0}".format(hiOutput)

Solution

  • Pass the command as string, and pass shell=True:

    import pipes
    import subprocess
    
    avprobeCommand = """avprobe -of json -show_streams {0} | grep '"duration"' | sed -n 1p | sed 's/ //g'""".format(pipes.quote(hiOutput))
    output = subprocess.check_output(avprobeCommand, shell=True)
    

    UPDATE: argument should be escaped using pipes.quote. (Use shlex.quote if you use Python 3.3+).