Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running cmd in python

Tags:

python

cmd

Atm I have this as my code, the first line seems to work well but the 2nd gives errrors.

os.chdir('C://Users/Alex/Dropbox/code stuff/test')
subprocess.call('ffmpeg -i test%d0.png output.avi')

Also when I try to run it as this, it gives a 1s cmd flicker and then nothing happens

os.system('ffmpeg -i test%d0.png output.avi')
like image 965
Coolcrab Avatar asked May 25 '13 09:05

Coolcrab


People also ask

Can Python run CMD?

Python offers a series of command-line options that you can use according to your needs. For example, if you want to run a Python module, you can use the command python -m <module-name> . $ python3 -m hello Hello World! Note: module-name needs to be the name of a module object, not a string.

What is CMD in Python?

The Cmd class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.

Why does Python not show CMD?

The “Python is not recognized as an internal or external command” error is encountered in the command prompt of Windows. The error is caused when Python's executable file is not found in an environment variable as a result of the Python command in the Windows command prompt.


2 Answers

For the later generations looking for the answer, this worked. (You have to separate the command by the spaces.)

import os
import subprocess
os.chdir('C://Users/Alex/')
subprocess.call(['ffmpeg', '-i', 'picture%d0.png', 'output.avi'])
subprocess.call(['ffmpeg', '-i', 'output.avi', '-t', '5', 'out.gif'])
like image 78
Coolcrab Avatar answered Oct 03 '22 22:10

Coolcrab


I also use subprocess but in another way.

As @Roland Smith claimed, the preferred method is (which isn't really comfortable):

subprocess.call(['ffmpeg', '-i', 'test%d0.png', 'output.avi'])

The second method can be more comfortable to use but can have some problems:

subprocess.call('ffmpeg -i test%d0.png output.avi', shell=True)

Besides the fact that is suggested avoiding setting the shell parameter to "True", I had problems when the output folder contains round brackets, that is: "temp(5)/output.avi".

A more robust way is the following:

import subprocess
import shlex

cmd = shlex.split('ffmpeg -i test%d0.png output.avi')
subprocess.call(cmd)

To know more about shlex. In particular, for shlex.split:

Split the string s using shell-like syntax.

like image 34
Rosario Scavo Avatar answered Oct 03 '22 23:10

Rosario Scavo