Skip to content

Instantly share code, notes, and snippets.

@murarisumit
Last active August 3, 2021 07:07
Show Gist options
  • Save murarisumit/1b07f9dbcff3958a22a502bc57504d92 to your computer and use it in GitHub Desktop.
Save murarisumit/1b07f9dbcff3958a22a502bc57504d92 to your computer and use it in GitHub Desktop.
Execute command using python subprocess #python #subprocess #external-commands
#!/bin/bin/env python
import subprocess
#Exeternal Command with args
DPKG = ['dpkg', '-l']
# Execute the command
dpkg_process = subprocess.Popen(DPKG, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait till process to exit
out, error = dpkg_process.communicate()
# Get return status
rc = dpkg_process.returncode
# Get output data
cmd_out = out.splitlines()
for line in cmd_out[1:]:
print(line.decode('utf-8'))
# Use similar to get data from 'error' stream in case of error,
# Left for user to try it out.
#P.S : Script is verbose just to explain, can be more pythonic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment