sys module provides access to variables and functions that interact closely with the Python interpreter.
Module Import
Common Attributes
sys.argv
Command-line arguments passed to a Python script.sys.path
List of directories Python searches for modules.sys.platform
Platform identifier.sys.version
Python version information.Standard Streams
sys.stdin, sys.stdout, sys.stderr
Standard input, output, and error streams.Exit Functions
sys.exit()
Exit the program.int | str
default:"0"
Exit status code (0 for success, non-zero for error) or exit message
sys.exc_info()
Get information about current exception.Module and Import Functions
sys.modules
Dictionary of loaded modules.sys.meta_path
List of meta path finders.Size and Memory
sys.getsizeof()
Get size of an object in bytes.any
required
Object to get size of
int
Size in bytes
sys.getrecursionlimit() / sys.setrecursionlimit()
Get or set maximum recursion depth.System Information
sys.maxsize
Maximum value a variable of typePy_ssize_t can take.
sys.byteorder
Byte order of the system.sys.executable
Path to Python interpreter.Debugging and Profiling
sys.settrace()
Set trace function for debugging.sys.setprofile()
Set profiling function.Flags and Options
sys.flags
Command-line flags.Practical Examples
Command-Line Script
Platform-Specific Code
Progress Bar with stderr
Memory Usage Tracker
Complete Reference
Constants
Platform Constants
Platform Constants
sys.platform- Platform identifiersys.byteorder- Native byte order (‘little’ or ‘big’)sys.maxsize- Maximum Py_ssize_t valuesys.maxunicode- Maximum Unicode code point
Version Information
Version Information
sys.version- Version stringsys.version_info- Version tuplesys.hexversion- Version as single numbersys.api_version- C API version
Executable Information
Executable Information
sys.executable- Python interpreter pathsys.prefix- Installation prefixsys.base_prefix- Base installation prefixsys.exec_prefix- Platform-specific installation prefix
Functions
Exit Functions
Exit Functions
sys.exit(status)- Exit the interpretersys.excepthook(type, value, traceback)- Handle uncaught exceptions
Exception Functions
Exception Functions
sys.exc_info()- Current exception informationsys.last_type,sys.last_value,sys.last_traceback- Last exception
Debugging Functions
Debugging Functions
sys.settrace(func)- Set trace functionsys.gettrace()- Get trace functionsys.setprofile(func)- Set profile functionsys.getprofile()- Get profile function
Module Functions
Module Functions
sys.getrefcount(object)- Reference countsys.getsizeof(object)- Object size in bytessys.intern(string)- Intern string
Best Practices
sys.argv is always a list:
Always check length before accessing elements to avoid IndexError.
Related Modules
os
Operating system interfaces
platform
Platform identification
argparse
Command-line argument parsing
logging
Logging facility
