How Do I Execute a Program or Call a System Command in Python?
How can I call an external command within Python as if I had typed it in a shell or command prompt? What is the best way to execute a Python system command?
How Do I Execute a Program or Call a System Command in Python?
How can I call an external command within Python as if I had typed it in a shell or command prompt? What is the best way to execute a Python system command?
One way to execute a Python system command is by using os.system()
. This function lets you run system commands directly, and it feels like typing the command in a shell. Here’s an example:
import os
os.system('ls') # For Unix-based systems
# Or on Windows:
os.system('dir')
This approach is simple, and the output of the command will be displayed directly in the console. However, keep in mind that it doesn’t capture the output for you to use programmatically.
Building on Shilpa’s answer, a more modern and versatile approach to executing a Python system command is to use the subprocess
module, especially the subprocess.run()
function. It not only runs the command but also allows you to capture the output and errors. Here’s an example:
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout) # Displays the output of the command
This method is much more robust. For example, you can handle errors or manipulate the output programmatically. It’s preferred for most cases where you need more control over the command execution.
Netra’s approach using subprocess.run()
is powerful, but sometimes, you might just want to execute a command and focus only on whether it succeeded. For this, you can use subprocess.call()
, which also comes from the subprocess
module. It runs the Python system command and waits for it to finish, but it returns only the exit status code:
import subprocess
exit_code = subprocess.call(['ls', '-l']) # Unix-based systems
# Or on Windows:
# exit_code = subprocess.call(['dir'], shell=True)
print(f'Exit code: {exit_code}')
This is great when you only care about the command’s success or failure rather than capturing its output. It’s a lightweight way to work with system commands in Python.