Skip to content

Commit 5639a77

Browse files
committed
updating materials from final article
1 parent 0dc0884 commit 5639a77

16 files changed

+127
-217
lines changed

subprocess/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
# Python `subprocess` Examples
22

3-
Here are the examples for the Real Python article on the `subprocess` module.
3+
Here are supporting materials for the Real Python tutorial, [The `subprocess` Module: Wrapping Programs With Python](https://realpython.com/python-subprocess/).
4+
5+
Be aware that some examples are designed for particular operating systems. The `basics_unix.py` file won't work on Windows, for instance.

subprocess/choice_react_popen_read_write.py

Lines changed: 0 additions & 43 deletions
This file was deleted.

subprocess/combining_processes.py

Lines changed: 0 additions & 31 deletions
This file was deleted.

subprocess/create_new_project.py

Lines changed: 0 additions & 26 deletions
This file was deleted.

subprocess/create_project.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from argparse import ArgumentParser
2+
from pathlib import Path
3+
import subprocess
4+
5+
6+
def create_new_project(name):
7+
project_folder = Path.cwd().absolute() / name
8+
project_folder.mkdir()
9+
(project_folder / "README.md").touch()
10+
with open(project_folder / ".gitignore", mode="w") as f:
11+
f.write("\n".join(["venv", "__pycache__"]))
12+
commands = [
13+
[
14+
"python",
15+
"-m",
16+
"venv",
17+
f"{project_folder}/venv",
18+
],
19+
["git", "-C", project_folder, "init"],
20+
["git", "-C", project_folder, "add", "."],
21+
["git", "-C", project_folder, "commit", "-m", "Initial commit"],
22+
]
23+
for command in commands:
24+
try:
25+
subprocess.run(command, check=True, timeout=60)
26+
except FileNotFoundError as exc:
27+
print(
28+
f"Command {command} failed because the process "
29+
f"could not be found.\n{exc}"
30+
)
31+
except subprocess.CalledProcessError as exc:
32+
print(
33+
f"Command {command} failed because the process "
34+
f"did not return a successful return code.\n{exc}"
35+
)
36+
except subprocess.TimeoutExpired as exc:
37+
print(f"Command {command} timed out.\n {exc}")
38+
39+
40+
if __name__ == "__main__":
41+
parser = ArgumentParser()
42+
parser.add_argument("project_name", type=str)
43+
args = parser.parse_args()
44+
create_new_project(args.project_name)

subprocess/custom_exit.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

33
try:
4-
sys.exit(sys.argv[1])
5-
except IndexError:
6-
sys.exit(0)
4+
raise SystemExit(sys.argv[1])
5+
except IndexError as e:
6+
raise SystemExit(0) from e

subprocess/error_handling.py

Lines changed: 7 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,14 @@
11
import subprocess
22

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-
)
143

154
try:
16-
failed_process.check_returncode()
5+
subprocess.run(["python", "timer.py", "5"], timeout=10)
6+
except FileNotFoundError as exc:
7+
print(f"Process failed because the executable could not be found.\n{exc}")
178
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
9+
print(
10+
f"Process failed because did not return a successful return code. "
11+
f"Returned {exc.returncode}\n{exc}"
2412
)
2513
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")
14+
print(f"Process timed out.\n{exc}")

subprocess/popen_pipe.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import subprocess
2+
3+
ls_process = subprocess.Popen(["ls", "/usr/bin"], stdout=subprocess.PIPE)
4+
grep_process = subprocess.Popen(
5+
["grep", "python"], stdin=ls_process.stdout, stdout=subprocess.PIPE
6+
)
7+
8+
for line in grep_process.stdout:
9+
print(line.decode("utf-8").strip())

subprocess/popen_timer.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import subprocess
2+
from time import sleep
3+
4+
with subprocess.Popen(
5+
["python", "timer.py", "5"], stdout=subprocess.PIPE
6+
) as process:
7+
8+
def poll_and_read():
9+
print(f"Output from poll: {process.poll()}")
10+
print(f"Output from stdout: {process.stdout.read1().decode('utf-8')}")
11+
12+
poll_and_read()
13+
sleep(3)
14+
poll_and_read()
15+
sleep(3)
16+
poll_and_read()
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from time import sleep, perf_counter
1+
from time import perf_counter, sleep
22
from random import random
33

44
print("Press enter to play")
@@ -9,4 +9,4 @@
99
start = perf_counter()
1010
input()
1111
end = perf_counter()
12-
print(f"You reacted in {end - start} seconds!\nGoodbye!")
12+
print(f"You reacted in {(end - start) * 1000:.0f} milliseconds!\nGoodbye!")

0 commit comments

Comments
 (0)