Skip to content

Instantly share code, notes, and snippets.

@murarisumit
Last active September 9, 2022 18:27
Show Gist options
  • Save murarisumit/da6d7e3f54cab9474b935d3a75c23e8a to your computer and use it in GitHub Desktop.
Save murarisumit/da6d7e3f54cab9474b935d3a75c23e8a to your computer and use it in GitHub Desktop.
Piping command using subprocess #subprocess #python
#!/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)
# Pipe output of dpkg to grep
grep_process = subprocess.Popen(['grep', 'lsof'], stdin=dpkg_process.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait till process to exit
out, error = grep_process.communicate()
# Get return status
rc = grep_process.returncode
# Get output data
cmd_out = out.splitlines()
for line in cmd_out:
print(line.decode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment