Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Magic Methods
0/1
Python
About Lesson

The sys module provides access to system-specific parameters and functions. It is mainly used for interacting with the Python runtime environment.

Key Functions and Attributes in sys module:

  • Command-Line Arguments:
    • sys.argv: A list of command-line arguments passed to a Python script (first element is the script name).

Example:

Python
import sys
print(sys.argv)  # If the script is called "example.py", prints: ['example.py', 'arg1', 'arg2']

Exit the Program:

  • sys.exit([status]): Exits the Python program with an optional exit status (0 for success, non-zero for failure).

Example:

Python
import sys
sys.exit(0)  # Exits the program with success status

Standard Input, Output, and Error Streams:

  • sys.stdin: Input stream (used for reading input from the user).
  • sys.stdout: Output stream (used for printing).
  • sys.stderr: Error stream (used for printing error messages).

System-Specific Information:

  • sys.platform: Returns the name of the operating system (e.g., ‘linux’, ‘win32’, etc.).
  • sys.version: Returns the Python version in use.

Example:

Python
import sys
print(sys.version)  # Example: '3.9.1 (default, Jan 27 2021, 08:17:35) [GCC 8.3.0]'

Memory Management:

  • sys.getsizeof(object): Returns the size of an object in bytes.

Example:

Python
import sys
x = [1, 2, 3]
print(sys.getsizeof(x))  # Prints the size of the list in bytes