sys
Summary of knowledge points of Python sys library:
- 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))
- 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')
- 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()))
- 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()
- 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.