snippetpythonCriticalCanonical
How do I execute a program or call a system command?
Viewed 0 times
programhowcallcommandexecutesystem
Problem
How do I call an external command within Python as if I had typed it in a shell or command prompt?
Solution
Use
Another common way is
On Python 3.4 and earlier, use
subprocess.run:import subprocess
subprocess.run(["ls", "-l"])
Another common way is
os.system but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run is generally more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc.). Even the documentation for os.system recommends using subprocess instead.On Python 3.4 and earlier, use
subprocess.call instead of .run:subprocess.call(["ls", "-l"])
Context
Stack Overflow Q#89228, score: 5965
Revisions (0)
No revisions yet.