In Python, you can execute Unix/Linux commands using the subprocess module. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
Here are some examples of how you can use the subprocess module to execute Unix/Linux commands in Python:
- Running a simple command: The following code runs the
lscommand and prints the output:
import subprocess
result = subprocess.run(["ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())
- Capturing the return code: The following code runs the
lscommand and captures the return code:
import subprocess
result = subprocess.run(["ls"])
print("Return code:", result.returncode)
- Running a command with arguments: The following code runs the
lscommand with the-largument:
import subprocess
result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())
- Running a shell command: The following code runs a shell command to print the current working directory:
import subprocess
result = subprocess.run("pwd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())
Note: When executing shell commands, it’s important to be careful about the input you pass to the command, as it can introduce security vulnerabilities if you pass untrusted input without proper escaping.