Reputation: 65
I have a huge command to run an executable with multiple parameters. It goes like this:
ffmpeg.exe -f dshow -y -video_size 1920x1080 -rtbufsize 1404000k -r 30 -i video="HD Video 2 (TC-2000HDMI Card)" -threads 2 -vcodec copy -ar 48000 -ac 1 -acodec pcm_s16le -t 60 c:/output.avi
I am using subprocess.Popen
for this but not sure how to pass so many arguments using python 2.7
I have gone through many posts, one of them being this. I could not make it work for multiple arguments.
Need help regarding this.
Upvotes: 1
Views: 2785
Reputation: 414149
.exe
suggests that you are on Windows where the native interface to specify a command to run is a string i.e., paste the string as is:
#!/usr/bin/env python
import subprocess
subprocess.check_call('ffmpeg.exe -f dshow -y -video_size 1920x1080 '
'-rtbufsize 1404000k -r 30 '
'-i video="HD Video 2 (TC-2000HDMI Card)" '
'-threads 2 -vcodec copy -ar 48000 -ac 1 -acodec pcm_s16le '
r'-t 60 c:\output.avi')
Note: the command is split into several literals only to spread it over multiple lines for readability. 'a' 'b'
literals coalesce into 'ab'
in Python.
If the command is not a literal string then it might be more convient to use a list, to specify the command:
#!/usr/bin/env python
import subprocess
nthreads = 2
width, height = 1920, 1080
filename = r'c:\output.avi'
subprocess.check_call([
'ffmpeg', '-f', 'dshow', '-y',
'-video_size', '%dx%d' % (width, height),
'-rtbufsize', '1404000k', '-r', '30',
'-i', 'video=HD Video 2 (TC-2000HDMI Card)',
'-threads', str(nthreads), '-vcodec', 'copy', '-ar', '48000', '-ac', '1',
'-acodec', 'pcm_s16le', '-t', '60',
filename])
Note: if only a name without a path and file extension is given then .exe
is appended automatically. This also makes the second form more portable.
To avoid escaping backslash in Windows paths, raw string literals could be used i.e., you could write r'C:\User\...'
instead of 'C:\\User\\...'
.
Upvotes: 1
Reputation: 8813
The example from subprocess.Popen
shows an example of parsing a complex command line correctly for passing to Popen
:
>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
Combining that with Python's triple quoting to allow for most quote varieties would give you something like this (haven't run it, sorry for the long command line):
import shlex, subprocess
p = subprocess.Popen(slex.split("""ffmpeg.exe -f dshow -y -video_size 1920x1080 -rtbufsize 1404000k -r 30 -i video="HD Video 2 (TC-2000HDMI Card)" -threads 2 -vcodec copy -ar 48000 -ac 1 -acodec pcm_s16le -t 60 c:/output.avi"""))
Upvotes: 1