Python Execute Unix / Linux Command Examples

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:

  1. Running a simple command: The following code runs the ls command and prints the output:
import subprocess

result = subprocess.run(["ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())

  1. Capturing the return code: The following code runs the ls command and captures the return code:
import subprocess

result = subprocess.run(["ls"])
print("Return code:", result.returncode)

  1. Running a command with arguments: The following code runs the ls command with the -l argument:
import subprocess

result = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(result.stdout.decode())

  1. 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.

(www.sullivansusa.net)

Leave a Comment