sys
Access to the interpreter: command-line arguments, ending the program, the Python version, and streams.
Example
#import sys
if len(sys.argv) < 2:
print("Usage: python greeting.py NAME")
sys.exit(1)
name = sys.argv[1]
print(f"Hello, {name}!")
print(sys.argv)Hello, Emma! ['greeting.py', 'Emma']
The result for the command python greeting.py Emma. Run without an argument, the program prints the usage instructions and exits with code 1.
Definition and usage
#The sys module gives access to information and settings of the Python interpreter itself. The most commonly used parts are the sys.argv list of command-line arguments and the sys.exit() function, which ends the program with a given exit code.
sys.argv[0] is the name of the script being run, and the following items are the arguments typed after it, always as strings. An exit code of 0 means success, and any other number means an error. It is read by shell scripts and tools that run your program.
The module also provides the standard streams sys.stdin, sys.stdout, and sys.stderr, the interpreter version in sys.version_info, the system name in sys.platform, and the list of directories searched on import in sys.path.
Syntax
#import sys
sys.argv
sys.exit(code)
sys.version_info
sys.stderrMore examples
#import sys
if sys.version_info >= (3, 10):
print("The Python version is sufficient")
else:
print("This program requires Python 3.10 or newer")
print(sys.version_info.major)
print(sys.getrecursionlimit())getrecursionlimit() returns the maximum depth of recursive calls, 1000 by default.
import sys
def fail(message):
print(f"Error: {message}", file=sys.stderr)
sys.exit(1)
print("Loading data...")
fail("missing file course.json")
print("This line will not run")The second line goes to the error stream (stderr), so redirecting with python app.py > log.txt will write only the first one to the file. The program exits with code 1.
Good practices
#- For elaborate command-line arguments, with options and automatic help, use the
argparsemodule instead of readingsys.argvby hand. - Arguments in
sys.argvare strings. Convert numbers withint()and handle an invalid value. - Print error messages to
sys.stderr, so they do not get mixed up with the programโs actual output.
Related entries
#- osWorking with the operating system: paths, directories, files, and environment variables.
- print()Writes values to standard output, which is the console by default.
- input()Reads a line of text typed by the user in the console.
- importLoads a module, or selected names from a module, into the current file.
- raiseRaises an exception, signaling an error or a disallowed situation.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.