Last active
September 28, 2024 17:45
-
-
Save gdanko/70aecaf7605b9451db13558f2cc7559d to your computer and use it in GitHub Desktop.
Simulating piping one command to another using Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This specific example is using the MacOS Sequoia version of
ps
.