← Back to Chapters

Python sys Module

? Python sys Module

? Quick Overview

The sys module in Python gives you direct access to interpreter-level functions, environment details, command-line arguments, I/O streams, and system-specific parameters.

? Key Concepts

  • Reading Python version and platform info
  • Handling command-line arguments with sys.argv
  • Using standard input/output/error streams
  • Checking and modifying module search paths
  • Gracefully exiting Python scripts

? Syntax / Theory

You need to import the module before using any of its properties or functions:

? Import sys Module
import sys
print(sys.version)    # Python version
print(sys.platform)   # OS platform
? Command-Line Arguments
# Save as example.py
import sys
print(sys.argv)  # List of command line arguments
? Standard Input, Output, and Error
sys.stdout.write("Hello World\n")   # Write to standard output
sys.stderr.write("This is an error message\n")   # Write to standard error stream
? Module Search Path
print(sys.path)  # List of directories Python searches for modules
? Exiting Python
sys.exit()      # Exit with default status code 0
sys.exit(1)     # Exit with a custom error code

? Live Output / Explanation

What Happens?

  • sys.argv returns a list of command-line arguments where index 0 is the script name.
  • sys.stdout writes text directly to the console.
  • sys.stderr is typically shown in red in terminals and used for error logging.
  • sys.path helps you debug module import errors.
  • sys.exit() stops the script immediately.

? Tips

  • Use sys.argv to manage command-line tools and scripts.
  • sys.path is very helpful when debugging import issues.
  • Terminate scripts gracefully using sys.exit().
  • You can redirect sys.stdout and sys.stderr to files for logging purposes.

? Try It Yourself

  • Write a script that prints all command-line arguments except the script name.
  • Redirect sys.stdout to a file and write some text.
  • Print Python version and platform using sys.version and sys.platform.
  • Exit a script with a custom code if a user input condition is not met.