Python——sys模块

sys 模块

This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter.


环境变量

1
2
3
4
5
>>> import sys # 记住要调用模块 此文章后边不再写
>>> sys.path
['', '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
# 环境变量
# 可以通过 sys.path.append() 来添加

查看已经加载的模块

1
2
>>> sys.modules
# 你就可以看到你已经加载的模块,由于我这边加载的模块巨多,不写了

获取终端调用时的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> sys.argv
[''] # 这里我在terminal中测试的代码
# 在pycharm, file:sys_argv.py
print(sys.argv) 这里我们可以看到 sys.argv 是一个列表
# ['/Users/ooc/Desktop/Python/sys模块.py']
print(sys.argv[0])
# /Users/ooc/Desktop/Python/sys模块.py

# file:sys_argv.py
#
import sys
print(sys.argv[2])
# file: sys_argv.py
# file_path: /Users/ooc/Desktop/Python/sys_argv.py
# terminal
oOCs-MBP:~ ooc$ python3 /Users/ooc/Desktop/Python/sys_argv.py 1 4 9 10
4 # 获取终端调用时的参数 第一个元素是程序本身路径

获取解释器的版本信息

1
2
3
4
>>> import sys
>>> sys.version
'3.7.0 (default, Aug 22 2018, 15:22:33) \n[Clang 9.1.0 (clang-902.0.39.2)]'
# 当前解释器使用的信息

获取当前平台名称

1
2
>>> sys.platform
darwin # MacOS

int类型支持的最大值

1
2
>>> sys.maxsize # 貌似python2中好像是,sys.maxint
9223372036854775807

最大的Unicode值

1
2
>>> sys.maxunicode
1114111

中间结束程序

1
2
3
4
5
>>> sys.exit() # 默认为0
# 执行到这行代码时就退出程序
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is an integer, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system

终端复制文件工具

1
2
3
4
5
6
7
8
9
# 原文件路径
source = sys.argv[1]
# 目标文件路径
dispath = sys.argv[2]

with open(source,'rb') as f:
data = f.read()
with open(dispatch,'wb') as f2:
f2.write(data)