Python sys

The sys module provides functionalities to interact with the Python interpreter. It gives access to variables and functions that control runtime behavior, manage command-line arguments, handle input/output, and monitor system-specific parameters.

1. Accessing Command-Line Arguments

sys.argv stores command-line arguments as a list. The first item is the script name, followed by any additional arguments.
import sys

# Print all command-line arguments
print("Command-line arguments:", sys.argv)

# Access individual arguments
for i, arg in enumerate(sys.argv):
    print(f"Argument {i}:", arg)

Example Output:

Command-line arguments: ['script.py', 'arg1', 'arg2']
Argument 0: script.py
Argument 1: arg1
Argument 2: arg2
Explanation: When running python script.py arg1 arg2, sys.argv holds the script name and arguments.

2. Exiting a Program

Use sys.exit() to terminate a program. You can provide an optional exit status, where 0 is typically "successful" and other values indicate an error.
# Exit with a status code
sys.exit("Exiting the program with an error")

Example Output:

Exiting the program with an error
Explanation: sys.exit() stops the program execution and optionally outputs an exit message.

3. Standard Input and Output

sys.stdin, sys.stdout, and sys.stderr represent the standard input, output, and error streams.
# Print to standard output
sys.stdout.write("This is standard output\n")

# Print to standard error
sys.stderr.write("This is standard error\n")

# Get user input from standard input
print("Enter a value:")
user_input = sys.stdin.read(5)  # Reads 5 characters
print("You entered:", user_input)

Example Output:

This is standard output
This is standard error
Enter a value:
abcde
You entered: abcde
Explanation: sys.stdin handles input, sys.stdout outputs messages, and sys.stderr outputs errors.

4. Version Information

sys.version gives the Python version as a string. sys.version_info provides a more structured version tuple.
# Display Python version
print("Python version:", sys.version)

# Display version info tuple
print("Version info:", sys.version_info)

Example Output:

Python version: 3.8.10 (default, Jun  4 2021, 15:09:15) 
[GCC 7.5.0]
Version info: sys.version_info(major=3, minor=8, micro=10, releaselevel='final', serial=0)
Explanation: sys.version gives detailed version info as a string, while sys.version_info offers easy access to individual version components.

5. Platform and System Information

sys.platform returns the OS platform identifier.
# Display platform
print("Platform:", sys.platform)

Example Output:

Platform: linux
Explanation: The sys.platform string identifies the OS, useful for cross-platform scripting.

6. Checking Recursion Limit

sys.getrecursionlimit() returns the current maximum recursion depth, while sys.setrecursionlimit() adjusts it.
# Display current recursion limit
print("Recursion limit:", sys.getrecursionlimit())

# Increase recursion limit
sys.setrecursionlimit(2000)
print("New recursion limit:", sys.getrecursionlimit())

Example Output:

Recursion limit: 1000
New recursion limit: 2000
Explanation: Changing the recursion limit helps manage recursion-heavy tasks but can risk a stack overflow if set too high.

7. Getting Module Search Path

sys.path lists directories Python searches for modules.
# Display Python module search paths
print("Module search paths:", sys.path)

Example Output:

Module search paths: ['/home/user', '/usr/local/lib/python3.8', ...]
Explanation: sys.path is a list of directories used when importing modules.

8. Byte Order

sys.byteorder shows the byte order used by the host machine ("little" or "big" endian).
# Display byte order
print("Byte order:", sys.byteorder)

Example Output:

Byte order: little
Explanation: Useful for low-level data manipulation, this indicates whether the system uses little-endian or big-endian byte order.

9. System Exit Codes

sys.exit() uses exit codes to indicate success (0) or failure (non-zero values) to the operating system.
try:
    # Exit with a custom status code
    sys.exit(1)
except SystemExit as e:
    print("Exited with code:", e.code)

Example Output:

Exited with code: 1
Explanation: The SystemExit exception allows custom exit codes, useful for signaling success or failure.

10. Memory Usage and Size of Objects

sys.getsizeof() returns the memory size of an object in bytes.
# Check size of a string and an integer
print("Size of 'Hello':", sys.getsizeof("Hello"), "bytes")
print("Size of 12345:", sys.getsizeof(12345), "bytes")

Example Output:

Size of 'Hello': 54 bytes
Size of 12345: 28 bytes
Explanation: sys.getsizeof() helps monitor memory use, especially for large data structures.

11. Interpreter Information

Additional interpreter information:
- sys.executable: Path to the Python interpreter executable.
- sys.prefix: Path to the Python installation directory.
# Interpreter path and installation prefix
print("Interpreter path:", sys.executable)
print("Python installation path:", sys.prefix)

Example Output:

Interpreter path: /usr/bin/python3
Python installation path: /usr
Explanation: These paths assist in locating the Python executable and installation directory.

Summary

The sys module provides powerful tools to interact with the Python runtime environment, including managing command-line arguments, system settings, interpreter configuration, memory management, and more.

Previous: Python os | Next: Python Json

<
>