Skip to content

Instantly share code, notes, and snippets.

@gdanko
Last active September 28, 2024 17:45
Show Gist options
  • Save gdanko/70aecaf7605b9451db13558f2cc7559d to your computer and use it in GitHub Desktop.
Save gdanko/70aecaf7605b9451db13558f2cc7559d to your computer and use it in GitHub Desktop.
Simulating piping one command to another using Python
#!/usr/bin/env python3
import subprocess
# This performs the equivalent of `ps -axm -o rss,comm | sort -rn -k 1 | head -n 20`
number_of_entries = 20
cmd1 = ['/bin/ps', '-axm', '-o', 'rss,comm']
cmd2 = ['sort', '-rn', '-k', '1']
cmd3 = ['head', '-n', str(number_of_entries)]
p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(cmd3, stdin=p2.stdout, stdout=subprocess.PIPE)
output = p3.stdout.read().decode()
print(output)
@gdanko
Copy link
Author

gdanko commented Sep 28, 2024

This specific example is using the MacOS Sequoia version of ps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment