Skip to content

Commit e05c2fe

Browse files
committed
piping and errors
1 parent 16c10ed commit e05c2fe

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

subprocess/combining_processes.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import subprocess
2+
3+
# Variations to do the same thing
4+
5+
ls_process = subprocess.run(["ls"], capture_output=True)
6+
grep_process = subprocess.run(["grep", "basics"], input=ls_process.stdout)
7+
8+
subprocess.run(
9+
["grep", "basics"],
10+
input=subprocess.run(["ls"], capture_output=True).stdout,
11+
)
12+
13+
ls_process = subprocess.run(["ls"], stdout=subprocess.PIPE)
14+
grep_process = subprocess.run(["grep", "basics"], stdin=ls_process.stdout)
15+
16+
# This one doesn't work
17+
print(subprocess.PIPE) # -1
18+
ls_process = subprocess.run(["ls"], stdout=-1)
19+
print(ls_process.stdout) # Successfully outputs
20+
grep_process = subprocess.run(
21+
["grep", "basics"], stdin=ls_process.stdout # Why does this not work??
22+
)
23+
24+
piped_process = subprocess.run(["bash", "-c", "ls | grep basic"])
25+
26+
27+
with open("buffer", "w") as buffer:
28+
ls_process = subprocess.run(["ls"], stdout=buffer)
29+
30+
with open("buffer", "r") as buffer:
31+
grep_process = subprocess.run(["grep", "basic"], stdin=buffer)

subprocess/custom_exit.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import sys
2+
3+
try:
4+
sys.exit(sys.argv[1])
5+
except IndexError:
6+
sys.exit(0)

subprocess/error_handling.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import subprocess
2+
3+
try:
4+
_ = subprocess.run(
5+
["python", "custom_exit.py", "1"], check=True, capture_output=True
6+
)
7+
except subprocess.CalledProcessError as exc:
8+
print(exc)
9+
10+
11+
failed_process = subprocess.run(
12+
["python", "custom_exit.py", "1"], capture_output=True
13+
)
14+
15+
try:
16+
failed_process.check_returncode()
17+
except subprocess.CalledProcessError as exc:
18+
print(exc)
19+
20+
21+
try:
22+
_ = subprocess.run(
23+
["python", "timer.py", "5"], capture_output=True, timeout=1
24+
)
25+
except subprocess.TimeoutExpired as exc:
26+
print(exc)
27+
28+
29+
try:
30+
_ = subprocess.run(["non_existent_program"])
31+
except FileNotFoundError as exc: # Subclass of OSError
32+
print(exc)
33+
34+
35+
try:
36+
_ = subprocess.run(
37+
["python", "non_existent_file"], check=True, capture_output=True
38+
)
39+
except subprocess.CalledProcessError as exc:
40+
if exc.returncode == 2:
41+
print("Python couldn't find the file")

0 commit comments

Comments
 (0)