How to call external commands from Python
You can use the subprocess module in the Python standard library:
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()

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.
Related Topics
- Keywords in Python
- Python Operator - Types of Operators in Python
- Python Variables and Data Types
- Python Shallow and deep copy operations
- Python Datatype conversion
- Python Mathematical Function
- Basic String Operations in Python
- Python Substring examples
- How to check if Python string contains another string
- Check if multiple strings exist in another string : Python
- Memory Management in Python
- Python Identity Operators
- What is a None value in Python?
- How to Install a Package in Python using PIP
- How to update/upgrade a package using pip?
- How to Uninstall a Package in Python using PIP
- How to use f-string in Python
- Python Decorators (With Simple Examples)
- Python Timestamp Examples