sys 是python的内置模块,提供一个接口与python解释器交互
python源码对模块sys的定义:
sys — System-specific parameters and functions sys提供系统级别的特殊参数和函数的一个模块,最高级别,可以改一些python解释器的安装配置文件等的级别。在低一点的级别是用户级别,可以调用模块或包,但是不能更改的。
This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. 这个模块对一些解释器的变量的接口和与解释强烈交互的函数。
几种常用的方法
- sys.modules
This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail. # 返回已经加载到给python开辟的内存空间里面的已经缓存的模块。
sys.path
A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. 返回的是一个列表包含系统环境变量,复制过来了,列表中第一个值是本文件所在的路径,第二个值是上级路径,剩下的就是系统用户本身的环境变量。最后一个是pycharm的环境变量(如果用别的编辑器,就是对应的环境变量。)sys.argv
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’. If no script name was passed to the Python interpreter, argv[0] is the empty string.
在命令行模式下,调用python解释器,然后执行py文件例:
在py文件中的代码是:
import sys
print(sys.argv)
import sys
# print(sys.argv) # ['D:/学习资料/Daily Code and experience/day23 时间模块/4. sys模块i.py']
# print(sys.modules) # 查看当前内存空间中所有的模块和这个模块的内存空间
# print(sys.path) # 获取系统环境变量,相当于python的内置函数,开机就会把这些路径存到内存里