kieran
kieran

Reputation: 548

sending variables to subprocess call with spaces - python 2.7

I want to add ffmpeg options to a variable and later use it in a subprocess call. If the variable contains one word, all is well, but if it contains more than one, I get errors. I am working on a larger script and I will need to have extra options such as this for certain codecs. How can I get this working?

The following works perfectly for me:

import subprocess
import sys

video_codec = 'libx264'
output = sys.argv[1] + '.mkv'
subprocess.call(['ffmpeg',
            '-i',sys.argv[1], 
            '-c:v',video_codec,
            '-c:a','copy',         
            output])    

Once I introduce new options/spaces to video_options as such:

video_codec = "'libx264', '-pix_fmt', 'yuv420p'"

I get an ffmpeg error:

Unknown encoder ''libx264', '-pix_fmt', 'yuv420p''

If I remove the double quotes and just use video_codec = 'libx264', '-pix_fmt', 'yuv420p'

I get a python error: Traceback (most recent call last): File "testo.py", line 10, in <module> output])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call return Popen(*popenargs, **kwargs).wait() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child raise child_exception TypeError: execv() arg 2 must contain only strings

Upvotes: 0

Views: 577

Answers (1)

Cargo23
Cargo23

Reputation: 3189

Eric Renouf has it right, but don't create a string, its less reliable. You just have to break apart your config like this:

video_codecs = ['libx264', '-pix_fmt', 'yuv420p']
output = sys.argv[1] + '.mkv'
cmd_list = ['ffmpeg',
        '-i',sys.argv[1], 
        '-c:v']
cmd_list += video_codecs
cmd_list += ['-c:a','copy',         
        output]
subprocess.call(cmd_list)

I'm not sure if the order matters, so I preserved it here, if order doesn't matter, you can just combine the last line with the third line.

Upvotes: 2

Related Questions