Python (Scripting) - Native operating system commands
by
Jeremy Canfield |
Updated: April 15 2024
| Python (Scripting) articles
subprocess can be used to run a command on the same system as your Python program. Here is the minimal boilerplate code without any error handling to create the /tmp/foo directory on the same system as your Python program.
#!/usr/bin/python3
import subprocess
subprocess.Popen("mkdir /tmp/foo", shell=True)
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import subprocess
try:
subprocess.Popen("mkdir /tmp/foo", shell=True)
except Exception as exception:
print(exception)
else:
print(f"successfully created the /tmp/foo directory")
Almost always, you are going to want to capture both stdout and stderr.
#!/usr/bin/python3
import subprocess
command = "pwd"
try:
stdout, stderr = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
except Exception as exception:
print(f"got the following exception: {exception}")
else:
stdout = stdout.decode('utf-8').strip()
stderr = stderr.decode('utf-8').strip()
if stdout:
print(f"stdout = {stdout}")
if stderr:
print(f"stderr = {stderr}")
Did you find this article helpful?
If so, consider buying me a coffee over at