Skip to content

Instantly share code, notes, and snippets.

@donutheist
Last active September 28, 2024 17:45
Show Gist options
  • Select an option

  • Save donutheist/70aecaf7605b9451db13558f2cc7559d to your computer and use it in GitHub Desktop.

Select an option

Save donutheist/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)
@donutheist
Copy link
Author

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