How to call external commands from Python

Python subprocess module allows you to spawn new processes, connect to their input/output and obtain their return codes. The advantage of subprocess module is that it is more flexible, this means that you can get the stdout, stderr, the "real" status code, better error handling, etc.

You can use the subprocess module in the Python standard library to call external commands from Python:

import subprocess subprocess.run(['C:\\Windows\\System32\\Notepad.exe'])
import subprocess subprocess.run(["ls", "-l"])

On Python 3.4 and earlier, use subprocess.call() instead of .run():

import subprocess subprocess.call(['C:\\Windows\\System32\\Notepad.exe'])
import subprocess subprocess.call(["ls", "-l"])

Python subprocess()

How to execute an external program  from python

Here is a working code that opens a text file using notepad. First field is the command itself and second field is argument.

import subprocess subprocess.run(['C:\\Windows\\System32\\Notepad.exe', 'D:\\myFile.txt'])

Running Python code

You can use subprocess to run a Python script on Windows/Linux/OS X.

import sys import subprocess proc = subprocess.Popen([sys.executable, "D:\\nest.py"]) proc.communicate()

Python sys.executable - the full path to the current Python executable, which can be used to run the script.

Python os.system

You can also use os.system() method to call an external command from Python. The os.system() method execute the command (a string) in a subshell. Whenever this method is used then the respective shell of the Operating System is opened and the command is executed on it.

import os cmd = 'date' os.system(cmd)

This command is useful because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. However, while this is useful, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.

Conclusion

To call external commands from Python, you can use the subprocess module, which provides functions to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. The subprocess.run() function is a simple and recommended way to execute external commands and capture their output, making it convenient to interact with other programs and shell commands from within Python scripts.