![](/img/trans.png)
[英]Executing A complex Shell command read as String from a File in Python
[英]Python complex string interpolation on shell command
我有一個要使用python腳本執行的shell命令。 它是ffmpeg
, grep
, gawk
和其他幾個ffmpeg
選項的組合。
命令
ffmpeg -i http://0.0.0.0:8080/stream/video.mjpeg -vcodec copy -map 0 -f segment -segment_time 2 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2>&1 | grep --line-buffered -Eo "segment:.+ended" | gawk -F "'" '{print $2; system("")}'
如果在終端上運行此命令,則應返回一個字符串
capture-00001.mp4
現在,我的目標是在Python3上使用subprocess
進程來運行它。 由於該命令使用單引號和雙引號混合時相當復雜,因此需要正確對待它,否則EOL while scanning string literal
, invalid syntax
等時會抱怨EOL while scanning string literal
。
我已經嘗試了幾種字符串格式化方法,但是沒有用。 以下是我嘗試過的方法之一。
腳本
import os
import datetime
import subprocess
first = "segment:.+ended"
second = "'"
third = '{print $2; system("")}'
if __name__ == "__main__":
fScript = "ffmpeg -i http://0.0.0.0:8080/stream/video.mjpeg -vcodec copy -map 0 -f segment -segment_time 2 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2>&1 | grep --line-buffered -Eo {} | gawk -F {} {}".format(first, second, third)
try:
result = subprocess.check_output(fScript, shell=True).decode('utf-8')
print(result)
except subprocess.CalledProcessError as e:
print(e.output)
感謝@NathanBlaine的建議,在這里使用帶有r
的標記字符串文字非常適合我的用例。 每天樂於學習新事物。 :)
不過,我無法使用check_output
檢索字符串結果。 相反, subprocess.call
設法返回了預期的字符串。 這是工作代碼。
import os
import datetime
import subprocess
if __name__ == "__main__":
fScript = r"""ffmpeg -i http://0.0.0.0:8080/stream/video.mjpeg -vcodec copy -map 0 -f segment -segment_time 2 -loglevel 40 -segment_format mp4 capture-%05d.mp4 2>&1 | grep --line-buffered -Eo "segment:.+ended" | gawk -F "'" '{print $2; system("")}'"""
try:
result = subprocess.call(fScript, stderr=subprocess.STDOUT, shell=True).decode('utf-8')
print(result)
except subprocess.CalledProcessError as e:
print(e.output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.