[python] One hour to master the sys module from entry to proficiency series

sys

Summary of knowledge points of Python sys library:

  1. sys.argv

sys.argv is a list that contains the list of command line parameters, and the parameters passed in by the command line can be obtained through sys.argv. Where sys.argv[0] represents the script name.

Sample code:

import sys

print("脚本名:", sys.argv[0])
print("参数列表:", str(sys.argv))
  1. sys.path

sys.path is a list of paths where the Python interpreter looks for modules. Custom module paths can be added via the sys.path.append() method.

Sample code:

import sys

print("Python解释器查找模块的路径列表:", sys.path)

# 添加自定义模块路径
sys.path.append('/path/to/custom/module')
  1. sys.modules

sys.modules is a dictionary containing all modules that have been imported in the current Python interpreter. The names of all imported modules can be obtained by the sys.modules.keys() method.

Sample code:

import sys

print("已导入的所有模块:", list(sys.modules.keys()))
  1. sys.stdin、sys.stdout、sys.stderr

sys.stdin, sys.stdout, and sys.stderr represent standard input, standard output, and standard error output, respectively. Redirection of input and output can be achieved by redirecting these streams.

Sample code:

import sys

# 重定向标准输出
sys.stdout = open('output.txt', 'w')
print('Hello, World!')
sys.stdout.close()

# 重定向标准错误输出
sys.stderr = open('error.txt', 'w')
print(1 / 0)
sys.stderr.close()
  1. sys.exit()

The sys.exit() method is used to exit the program, and an integer parameter can be passed in as the exit status code.

Sample code:

import sys

sys.exit(0)  # 正常退出
sys.exit(1)  # 异常退出

Summarize:

The sys library provides some functions and variables that interact with the Python interpreter and the system, including command line parameters, module imports, standard input and output, program exit, etc. Proficiency in the use of the sys library can improve the reliability and portability of Python programs.

Guess you like

Origin blog.csdn.net/qq_41604569/article/details/131306903