Any way to assign terminal output to variable with python?
Question:
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
Am I doing the output redirect wrong? Or is there simply no way to pipe the terminal output back into python?
Answers:
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
You probably want subprocess.Popen.
os.system returns the exit code of the executed command, not its output. To do this you would need to use either commands.getoutput (deprecated) or subprocess.Popen:
from subprocess import Popen, PIPE
stdout = Popen('your command here', shell=True, stdout=PIPE).stdout
output = stdout.read()
Much simplest way
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)
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
Am I doing the output redirect wrong? Or is there simply no way to pipe the terminal output back into python?
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
You probably want subprocess.Popen.
os.system returns the exit code of the executed command, not its output. To do this you would need to use either commands.getoutput (deprecated) or subprocess.Popen:
from subprocess import Popen, PIPE
stdout = Popen('your command here', shell=True, stdout=PIPE).stdout
output = stdout.read()
Much simplest way
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)