Python

OS, sys, argparse & subprocess

36 flashcards · answers and spaced-repetition review in the KnowCard app

You run an external tool with subprocess.run(["mytool", "--check"]). It fails (exit code 1) but your Python script keeps going as if nothing happened. How do you make the failure raise?
What does `r.stdout` hold after this, and why is `text=True` important? ``` r = subprocess.run( ["echo", "hi"], capture_output=True, text=True) ```
What are sys.stdin, sys.stdout, and sys.stderr, and why send error/diagnostic messages to stderr rather than stdout?
You read a config value with os.environ["API_KEY"]. It works on your machine but crashes with KeyError on a fresh deploy where the var isn't set. What's the safe way to read it?
What does this print when run as `python prog.py hello`? ``` import sys print(len(sys.argv)) print(sys.argv[0]) ```
A script is called `python add.py 2 3` with this body. What does it print? ``` import sys print(sys.argv[1] + sys.argv[2]) ```
Why reach for argparse instead of just reading sys.argv yourself for a CLI that takes a couple of flags and arguments?
In argparse you add a positional like this, then read args.op1. The user runs the program with no arguments at all. What happens? ``` p.add_argument("op1", type=float) ```
What does this print, and what exit code does the process return? ``` import sys sys.exit("disk full") print("done") ```
By convention, what exit code does a program return on success, and what does a nonzero code mean to the shell?
You append a directory to sys.path at runtime so you can import a module from it. What is sys.path, and what's the gotcha with ordering?
You want to run Linux-specific code only on Linux. Why is checking sys.platform == "linux2" a fragile guard?
You want a feature that needs Python 3.8+. Why is comparing sys.version_info to the string "3.8" wrong, and what compares correctly?
Inside your script you call os.chdir("logs") and then later os.chdir("data"). The second call fails with FileNotFoundError even though ./data exists. Why?
You run os.system("grep error app.log") and want the matching lines in a Python variable. Why doesn't that work, and what should you use?
What is the single most important reason to pass a LIST to subprocess.run instead of a command string? ``` subprocess.run(["rm", filename]) ```
When is running subprocess.run(cmd, shell=True) dangerous, and what's the safer default?
You want --verbose to be a boolean flag (present means True) and --mode to store a fixed constant. Which add_argument action values do that?
By default argparse hands you every value as a str. How do you (a) auto-convert an argument to float and (b) restrict it to a fixed set of allowed values?
Two argparse constructor behaviors: how do you disable the automatic -h/--help, and how do you make omitted arguments simply not appear on the namespace at all?
You want a positional that accepts one or more operands gathered into a list. Which nargs value, and what do N, ?, and * mean?
In older code you see except os.error: wrapped around a file operation. What exception does os.error actually refer to?
You pass a bytes path to an os function, e.g. os.listdir(b"."). What type are the returned filenames, and what's the general rule?
Your machine has 4 physical cores, each with 2 hyperthreads. What does os.cpu_count() return, and what does os.getpid() give you?
os.system("ls") only returns the exit code. Using just the os module (no subprocess), how can you actually read a command's output?
You reassign sys.stdout to a file to capture output, then want the terminal back. What's the clean way to restore the original?
How can you check at runtime whether your code is running on CPython rather than another Python implementation?
sys.version_info is a tuple. What is sys.hexversion, and why is it convenient for a quick 'newer than X' test?
Your script needs to spawn another Python process using the same interpreter it is currently running under. Where do you get that interpreter's path?
You're about to pack binary data and need to know whether the host stores the most significant byte first. Which sys value tells you, and what are its two possible values?
sys.getwindowsversion() works on your colleague's Windows box but raises AttributeError on your Mac. Why?
In an interactive session >>> 42 echoes 42, yet print(42) doesn't use that same echo path. What controls the interactive echo, and what's the gotcha?
You want every uncaught exception in your app to be logged to a file instead of just dumping a traceback to the console. Which sys hook do you override?
In parser.add_argument("-o", "--operation", default="add"), what role does each of the three parts play?
On Windows you'd like options to start with / (e.g. /operation) instead of -. Can argparse do that?
After parse_args() you detect a semantically invalid argument combination in your own code. How do you report it argparse-style and abort?

Start learning today

Free to start — download the app or use it in your browser.

Get it on App StoreGet it on Google Play