簡體   English   中英

你如何處理Python中的管道和輸出?

[英]How do you handle pipes and output in Python?

我試圖在我的python腳本中執行此命令:

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

而且我一直在:

    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

我已經嘗試將args拆分了,但是我仍然為-of json -show_streams部分收到錯誤,對於記錄,它看起來像這樣:

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

將命令作為字符串傳遞,並傳遞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 :參數應該使用pipes.quote進行轉義。 (使用shlex.quote如果你使用Python 3.3+)。

在您的情況下,您可以將后處理移動到Python:

import json
from subprocess import check_output as qx

data = json.loads(qx(["avprobe", "-of", "json", "-show_streams", hiOutput]))
result = data["duration"]         # grep '"duration"'
             .partition("\n")[0]  # sed -n 1p
             .replace(" ", "")    # sed 's/ //g'

有關更一般的情況,請參閱如何使用subprocess.Popen通過管道連接多個進程?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM