How to call external commands from PythonYou 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()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. 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 codeYou 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.systemYou 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.
- 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