任何方式使用python将终端输出分配给变量? [英] Any way to assign terminal output to variable with python?
问题描述
我需要通过python抓取视频文件的持续时间,作为一个较大的脚本的一部分。我知道我可以使用ffmpeg来获取持续时间,但是我需要在python中将该输出保存为一个变量。我以为这可以工作,但是它的值为0:
I need to grab the duration of a video file via python as part of a larger script. I know I can use ffmpeg to grab the duration, but I need to be able to save that output as a variable back in python. I thought this would work, but it's giving me a value of 0:
cmd = 'ffmpeg -i %s 2>&1 | grep "Duration" | cut -d \' \' -f 4 | sed s/,//' % ("Video.mov")
duration = os.system(cmd)
print duration
我做输出重定向错误?或者是没有办法将终端输出管回到python?
Am I doing the output redirect wrong? Or is there simply no way to pipe the terminal output back into python?
推荐答案
os.system
返回指示命令成功或失败的返回值。它不返回stdout或stderr的输出。要获取stdout(或stderr)的输出,请使用 subprocess.Popen
。
os.system
returns a return value indicating the success or failure of the command. It does not return the output from stdout or stderr. To grab the output from stdout (or stderr), use subprocess.Popen
.
import subprocess
proc=subprocess.Popen('echo "to stdout"', shell=True, stdout=subprocess.PIPE, )
output=proc.communicate()[0]
print output
看到奇妙写的本周博客的Python模块。
这篇关于任何方式使用python将终端输出分配给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!