sys模块
sys模块
sys.argv
接受命令行传递的参数
第一个参数时文件名称,后续为参数
脚本内容:
#!/usr/bin/python3
import sys
name="hello world"
print(name)
print("-------------------------------");
print("The list of command line arguments:\n", sys.argv)
print("-------------------------------");
for i in sys.argv:
print(i)
输出:
[root@localhost scripts]# python3 first.py hello1 hello2
hello world
-------------------------------
The list of command line arguments:
['first.py', 'hello1', 'hello2']
-------------------------------
first.py
hello1
hello2
sys.platform
在linux环境下:
sys.platform 为linux
在windows环境下:
sys.platform 为win32
sys.executable
脚本:
#!/usr/bin/python3
import sys
name="hello world"
print(name)
print("-------------------------------");
print("The list of command line arguments:\n", sys.argv)
print("-------------------------------");
for i in sys.argv:
print(i)
print(sys.platform)
print(sys.executable)
输出:
[root@localhost scripts]# python3 first.py hello1 hello2
hello world
-------------------------------
The list of command line arguments:
['first.py', 'hello1', 'hello2']
-------------------------------
first.py
hello1
hello2
linux
/usr/bin/python3
sys.modules
脚本:
#!/usr/bin/python3
import sys
name="hello world"
print(name)
print("-------------------------------");
print("The list of command line arguments:\n", sys.argv)
print("-------------------------------");
for i in sys.argv:
print(i)
print(sys.platform)
print(sys.executable)
print("-------------------------------");
print(sys.modules)
输出:
[root@localhost scripts]# python3 first.py hello1 hello2
hello world
-------------------------------
The list of command line arguments:
['first.py', 'hello1', 'hello2']
-------------------------------
first.py
hello1
hello2
linux
/usr/bin/python3
-------------------------------
{'builtins': , 'sys': , '_frozen_importlib': , '_imp': , '_warnings': , '_thread': , '_weakref': , '_frozen_importlib_external': , '_io': , 'marshal': , 'posix': , 'zipimport': , 'encodings': , 'codecs': , '_codecs': , 'encodings.aliases': , 'encodings.utf_8': , '_signal': , '__main__': , 'encodings.latin_1': , 'io': , 'abc': , '_weakrefset': , 'site': , 'os': , 'errno': , 'stat': , '_stat': , 'posixpath': , 'genericpath': , 'os.path': , '_collections_abc': , '_sitebuiltins': , 'sysconfig': , '_sysconfigdata_m_linux_x86_64-linux-gnu': }
sys.path
该属性是一个由字符串组成的列表,其中各个元素表示的是 Python 搜索模块的路径;在程序启动期间被初始化。
其中第一个元素(也就是path[0])的值是最初调用 Python 解释器的脚本所在的绝对路径;如果是在交互式环境下查看sys.path的值,就会得到一个空字符串。
sys.path
输出:
['/root/scripts', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
sys.exit
功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)
sys.stdin sys.stdout sys.err