18 Python’s sys module

Overview

        In the previous section, we introduced Python's os module, including: some commonly used attributes and functions in the os module. In this section, we will introduce Python’s sys module. The sys module provides access to variables used or maintained by the interpreter, as well as functions for interacting with the interpreter. Generally speaking, the sys module is responsible for the interaction between the program and the Python interpreter, and provides a series of functions and variables for controlling the Python runtime environment. For example: it provides some methods for interacting with the Python interpreter, including: obtaining command line parameters, handling the exit of the Python interpreter, etc.

        Below, we will introduce some commonly used properties and functions in the sys module one by one.

sys.version property

        sys.version is a string containing additional information such as the Python interpreter version number and compilation version number. It will be displayed when the Python interactive interpreter starts.

import sys

# 输出:3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)]
print(sys.version)

sys.version_info attribute

        sys.version_info is a tuple that contains five parts of information: major version number, minor version number, micro version number, release level ('alpha', 'beta', 'candidate' or 'final') and serial number. For example: for Python 3.8.5, sys.version_info will return (3, 8, 5, 'final', 0). The returned tuple can be used to compare Python versions.

import sys

# 输出:sys.version_info(major=3, minor=11, micro=4, releaselevel='final', serial=0)
print(sys.version_info)
if sys.version_info < (3, 0):
    print('can only run in Python 3.x')
    sys.exit()
else:
    print('Python version passed')

sys.platformProperty

        sys.platform is a string representing the platform on which the Python interpreter is running. If your Python interpreter is running on Windows, the value of sys.platform will be 'win32'; if your Python interpreter is running on Linux or Mac OS, the value of sys.platform will be 'darwin' or 'linux2' .

        This attribute can be used to write code that depends on a specific operating system. For example: if we need to use some libraries or functions that are only available on Windows, we can first check the value of sys.platform, and then choose which library or function to use as needed. Or give users a hint letting them know the program won't run on their current operating system.

import sys

# 输出:win32
print(sys.platform)

sys.path property

        sys.path is a Python list containing many directories. When we try to import a module, Python looks for that module in this list. The initial value of this list comes from the following three aspects: the directory of the input script, the PYTHONPATH environment variable, and the default path of the installation. This list can be modified so that Python looks for modules in the directories we specify. For example: if the module is in a non-standard directory, we can add that directory to sys.path so Python can find it.

        Note: Modifying sys.path will only affect the behavior of the current Python process and will not affect other processes or the Python interpreter.

import sys

# 输出:['F:\\', 
# 'C:\\Users\\H\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip', 
# 'C:\\Users\\H\\AppData\\Local\\Programs\\Python\\Python311\\DLLs', 
# 'C:\\Users\\H\\AppData\\Local\\Programs\\Python\\Python311\\Lib', 
# 'C:\\Users\\H\\AppData\\Local\\Programs\\Python\\Python311', 
# 'C:\\Users\\H\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages']
print(sys.path)

sys.argvproperty

        sys.argv is a Python list containing command line arguments. The first element of the list is the script name, which is the name of the program being called, and the remaining elements are the arguments passed to the program from the command line. For example: if you run python test.py arg1 arg2, then sys.argv will be ['test.py', 'arg1', 'arg2']. We can use sys.argv to get the command line arguments and process them as needed.

import sys

# 输出:['F:\\test.py']
print(sys.argv)

sys.stdout property

        sys.stdout is a Python file object that represents the system’s standard output stream. You can operate sys.stdout like a file, for example: write text. The content written to sys.stdout will be output to the console, which is the terminal or command line window. Note: Although we can operate sys.stdout like a file, it is not recommended because it may cause some unpredictable problems. If you need to output text, it is best to use the print() function instead of directly operating sys.stdout.

import sys

# 输出:Hello, CSDN
sys.stdout.write('Hello, CSDN\n')

sys.maxsizeproperty

        sys.maxsize is a Python integer representing the largest integer that Python can handle. This value is determined based on the number of bits and configuration of Python: in 32-bit Python, the value of sys.maxsize is 2147483647 (that is, 2 to the 31st power minus 1); in 64-bit Python, the value of sys.maxsize It is 9223372036854775807 (that is, 2 to the 63rd power minus 1). sys.maxsize can be used to check whether an integer will overflow after operations such as addition or multiplication. If you try to add a number larger than sys.maxsize to an integer, Python will throw an OverflowError.

import sys

# 输出:9223372036854775807
print(sys.maxsize)

sys.exit() function

        The sys.exit() function is used to trigger a system exit. It accepts an optional parameter, which can be an integer or an exception object. If the argument is an integer, then this integer will be used as the exit status of the Python interpreter; if the argument is an exception object, then the exception will be thrown; if no arguments are provided to this function, or the argument is None, then The Python interpreter will exit with status code 0. This function is usually used when you want to end the program immediately, or when handling fatal errors in the program.

import sys

a = 10
if a > 6:
    sys.exit(0)
else:
    print(a)

sys.getfilesystemencoding() function

        The sys.getfilesystemencoding() function is used to return the default encoding of the file system. This function replaces the sys.getdefaultencoding() function.

import sys

# 输出:utf-8
print(sys.getfilesystemencoding())

sys.getrecursionlimit() function

        The sys.getrecursionlimit() function is used to return the current recursion depth limit of the Python interpreter. This limit is a protection mechanism to prevent infinite recursion from crashing the program. In Python, each function call adds a new stack frame to the call stack, and each stack frame occupies some memory. If the function call level is too deep, the call stack will overflow and the program will crash. Note: Although you can use sys.setrecursionlimit(limit) to increase this limit, this is generally not recommended because it may cause a large amount of memory to be occupied, or even cause the program to crash.

import sys

# 输出:1000
print(sys.getrecursionlimit())

Guess you like

Origin blog.csdn.net/hope_wisdom/article/details/132950754