有没有办法用python将终端输出分配给变量?

有没有办法用python将终端输出分配给变量?,python,redirect,terminal,ffmpeg,Python,Redirect,Terminal,Ffmpeg,我需要通过python获取视频文件的持续时间,作为更大脚本的一部分。我知道我可以使用ffmpeg获取持续时间,但我需要能够将输出保存为python中的变量。我原以为这会起作用,但它给了我一个0的值: cmd = 'ffmpeg -i %s 2>&1 | grep "Duration" | cut -d \' \' -f 4 | sed s/,//' % ("Video.mov") duration = os.system(cmd) print duration 我是否做了输出重定

我需要通过python获取视频文件的持续时间,作为更大脚本的一部分。我知道我可以使用ffmpeg获取持续时间,但我需要能够将输出保存为python中的变量。我原以为这会起作用,但它给了我一个0的值:

cmd = 'ffmpeg -i %s 2>&1 | grep "Duration" | cut -d \' \' -f 4 | sed s/,//' % ("Video.mov")
duration = os.system(cmd)
print duration

我是否做了输出重定向错误?或者根本没有办法将终端输出传回python?

os.system
返回一个指示命令成功或失败的返回值。它不返回stdout或stderr的输出。要从stdout(或stderr)获取输出,请使用
subprocess.Popen

import subprocess
proc=subprocess.Popen('echo "to stdout"', shell=True, stdout=subprocess.PIPE, )
output=proc.communicate()[0]
print output

请参阅编写精良的。

您可能需要。

操作系统返回已执行命令的退出代码,而不是其输出。为此,您需要使用commands.getoutput(已弃用)或subprocess.Popen:

from subprocess import Popen, PIPE

stdout = Popen('your command here', shell=True, stdout=PIPE).stdout
output = stdout.read()
最简单的方法

import commands
cmd = "ls -l"
output = commands.getoutput(cmd)
import commands
cmd = 'ls'
output = commands.getoutput(cmd)
print output
#!/usr/bin/python3
import subprocess 
nginx_ver = subprocess.getstatusoutput("nginx -v")
print(nginx_ver)