The Python sys module provides access to functions and values concerning the program’s runtime environment, such as the command line parameters in sys.argv or the function sys.exit() to end the current process from any point in the program flow.
While cleanly separated into a module, it’s actually built-in and as such will always be available under normal circumstances.
Section 177.1: Command line arguments
if len(sys.argv) != 4: # The script name needs to be accounted for as well. raise RuntimeError("expected 3 command line arguments")
f = open(sys.argv, 'rb') # Use first command line argument.
start_line = int(sys.argv) # All arguments come as strings, so need to be
end_line = int(sys.argv) # converted explicitly if other types are required.
Note that in larger and more polished programs you would use modules such as click to handle command line arguments instead of doing it yourself.
The name of the executed script is at the beginning of the argv list. print('usage:', sys.argv, ' ')
You can use it to generate the path prefix of the executed program
(as opposed to the current module) to access files relative to that,
which would be good for assets of a game, for instance.
program_file = sys.argv
program_path = pathlib.Path(program_file).resolve().parent
Standard error stream
Error messages should not go to standard output, if possible. print('ERROR: We have no cheese at all.', file=sys.stderr)
f = open('nonexistent-file.xyz', 'rb')
except OSError as e:
Ending the process prematurely and returning an exit code
if len(sys.argv) != 4 or '--help' in sys.argv[1:]:
print('usage: my_program ', file=sys.stderr)
sys.exit(1) # use an exit code to signal the program was unsuccessful