Python (Scripting) - Native operating system commands
by
Jeremy Canfield |
Updated: March 23 2024
| Python (Scripting) articles
There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).
Here is an example of how subprocess can be used to run a command native to the operating system and to then print the stdout or stderr that is returned. strip is used to remove the new lines from the stdout/stderr output.
#!/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:
if stdout:
print(f"stdout = {stdout.strip()}")
if stderr:
print(f"stderr = {stderr.strip()}")
With Python 2, the output should be returned as a string, but with Python 3 the stdout and stderr is returned as bytes, so it's a good idea to include decode to convert bytes to string for Python 3.
stdout = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
Or like this, 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:
if stdout:
print(f"stdout = {stdout.decode('utf-8').strip()}")
if stderr:
print(f"stderr = {stderr.decode('utf-8').strip()}")
Did you find this article helpful?
If so, consider buying me a coffee over at