Skip to content
Foxipa
Code Completion 4 Challenges

Complete the subprocess code

Practice safe child-process invocation, input/output, nonzero statuses, and timeouts.

Intermediate ~10 min read

Challenge 1

Run the current Python interpreter to print a message, capture the output as text, and fail if the child fails.

python Your answer
import subprocess
import sys

result = subprocess.run(
    [sys.executable, "-c", "print('ready')"],
    
)
print(result.stdout.strip())

Press Ctrl⌘Enter to check your answer

Challenge 2

Send a string to the child's standard input and capture its uppercase response.

python Your answer
import subprocess
import sys

result = subprocess.run(
    [sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"],
    
)
print(result.stdout.strip())

Press Ctrl⌘Enter to check your answer

Challenge 3

Make a nonzero child exit raise CalledProcessError, then print the child's return code.

python Your answer
import subprocess
import sys

try:
    subprocess.run([sys.executable, "-c", "raise SystemExit(7)"], )
except subprocess.CalledProcessError as error:
    print(error.returncode)

Press Ctrl⌘Enter to check your answer

Challenge 4

Stop waiting if the child process takes longer than a short limit and handle the timeout.

python Your answer
import subprocess
import sys

try:
    subprocess.run([sys.executable, "-c", "import time; time.sleep(2)"], )
except subprocess.TimeoutExpired:
    print("timed out")

Press Ctrl⌘Enter to check your answer