Linux commands are very powerful and versatile. Many tasks that can be completed manually in the terminal can also be achieved programmatically using Python. Today, we’re going to delve into how to run Linux commands in Python with the help of the os and subprocess modules.
The ‘os’ Module
Python’s os module provides functions for interacting with the operating system, including running command-line commands. To run a Linux command, you can use the os.system() function.
import os os.system('ls')
In the above example, we’re running the ls command, which lists all files and directories in the current directory. The os.system() function takes the command as a string.
The ‘subprocess’ Module
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Essentially, it allows you to run command-line commands and capture their output. The subprocess.run() function can be used for this purpose.
import subprocess result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) print(result.stdout.decode('utf-8'))
In the example above, we’re running the ls -l command, which lists all files and directories in the current directory in long format. The subprocess.run() function takes the command as a list, where each item in the list is a part of the command. The output of the command is captured and can be used further in your Python program.
Running Linux commands in Python can be pretty straightforward with the os and subprocess modules. They provide flexibility and control over how you interact with the system, making it possible to automate and script tasks that would otherwise require manual input in a terminal.
It’s important to use these tools wisely and responsibly. Ensure you understand a command before you run it, as some commands can have destructive effects if used incorrectly.