In Python, we have a powerful module called subprocess
that allows us to execute operating system commands from our script. This feature can be extremely useful when we need to automate tasks or interact with the operating system directly.
Executing Basic OS Commands
To execute basic OS commands in Python, we can use the subprocess.run()
function. This function takes a list of command-line arguments as input and executes the specified command.
import subprocess
# Execute a simple 'ls' command in Linux
subprocess.run(['ls'])
# Execute a 'dir' command in Windows
subprocess.run(['dir'], shell=True)
Here, we use the subprocess.run()
function to execute the ls
command in Linux and the dir
command in Windows. Note that in Windows, we set the shell=True
parameter to enable the use of the command prompt.
Capturing Command Output
We can also capture the output of the executed command by setting the capture_output
parameter to True
. This allows us to retrieve the output and use it within our Python script.
import subprocess
# Execute a 'pwd' command in Linux and capture the output
result = subprocess.run(['pwd'], capture_output=True, text=True)
# Print the output
print(result.stdout)
In this example, we execute the pwd
command to print the current working directory in Linux, and then capture the output using the capture_output=True
parameter. The output can be accessed using the stdout
attribute of the result variable.
Running Shell Commands
If we want to execute a command using the shell syntax, we can pass the entire command as a single string and set the shell
parameter to True
.
import subprocess
# Execute a 'mkdir' command using shell syntax
subprocess.run('mkdir new_directory', shell=True)
This example demonstrates executing the mkdir
command to create a new directory named “new_directory” using the shell syntax.
Error Handling
When executing OS commands, it’s crucial to handle errors to ensure our script behaves as expected. We can check the return code of the executed command to determine its success or failure.
import subprocess
# Execute a nonexistent command
result = subprocess.run(['nonexistent_command'])
# Check the return code
if result.returncode != 0:
print("Command execution failed!")
Here, we execute a nonexistent command and check the return code using the returncode
attribute of the result variable. If the return code is non-zero, it indicates a failure.
Conclusion
With the subprocess
module in Python, executing OS commands becomes easier and more powerful. We can automate tasks, interact with the operating system, and capture command output seamlessly. However, it’s crucial to handle errors appropriately to ensure the stability of our scripts.