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:
On Python 3.4 and earlier, use subprocess.call() instead of .run():
Here is a working code that opens a text file using notepad. First field is the command itself and second field is argument.
Running Python code
You can use subprocess to run a Python script on Windows/Linux/OS X.
Python sys.executable - the full path to the current Python executable, which can be used to run the script.
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.
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.
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.