sys.argv is a list of command-line arguments passed to the script, with the script's own name as the first element. sys.exit(code) terminates the program immediately, optionally with an exit status code that other programs or shell scripts can check. sys.path is the list of directories Python searches when resolving an import statement, and modifying it, rarely necessary, changes where imports are found. sys.stdout and sys.stderr give direct access to the standard output and error streams, which is what print() uses internally by default.
1Understanding sys Module
sys.argv is a list of command-line arguments passed to the script, with the script's own name as the first element. sys.exit(code) terminates the program immediately, optionally with an exit status code that other programs or shell scripts can check. sys.path is the list of directories Python searches when resolving an import statement, and modifying it, rarely necessary, changes where imports are found. sys.stdout and sys.stderr give direct access to the standard output and error streams, which is what print() uses internally by default.
Use a nonzero exit code to signal failure from a command-line script, and zero for success — many surrounding tools and CI pipelines check this exit code to decide whether the script succeeded.
import sys
print(sys.argv)2Practical Example
Here is a real-world application of sys Module showing how it is used in production Python code.
import sys
def main():
if len(sys.argv) < 2:
print("Usage: script.py <name>", file=sys.stderr)
sys.exit(1)
print(f"Hello, {sys.argv[1]}!")
main()3Best Practices
Follow these guidelines when working with sys Module:
1. Use sys.argv, or better, the argparse module, to accept command-line arguments in scripts instead of hardcoding values
2. Call sys.exit() with a nonzero code to signal failure from a script, so calling shells/CI pipelines can detect it
3. Print diagnostic or error messages to sys.stderr instead of standard output, so they don't get mixed into a program's normal piped output
Tip: Use a nonzero exit code to signal failure from a command-line script, and zero for success — many surrounding tools and CI pipelines check this exit code to decide whether the script succeeded.
import sys
print(sys.argv)