一、介绍
二、方法
sys.argv[num] # 命令行输入参数
sys.version # python版本号,字符串
sys.version_info # 返回一个元组,有五个元素,用名称可以调用,用于版本信息
sys.paltform # 平台window、Linux
sys.path # 模块放置路径
sys.stdin.readline()[:-1] # 标准输入去除后面的/n
sys.stdout.write() # 标准输出
sys.stderr # 异常
sys.exit() # 退出程序,0正常,其余作为异常返回
sys.displayhook(value) # 显示东西时会被触发的hook
1、sys.argv()
允许从程序外部获取参数
import sys
print(sys.argv[0])
print(sys.argv[1])
调用方式
输出
2、sys.exit()
当参数为0时,正常退出,为其他时,作为异常返回
import sys
def exitfunc(value):
print(value)
sys.exit(0)
print("hello")
try:
sys.exit(1)
except SystemExit as value:
exitfunc(value)
print("come?")
输出
3、sys.path
与存储模块的路径有关
查看
import sys
print(sys.path)
添加新路径
import sys
sys.path.append('路径位置')
4、sys.modules()
全局字典,每当python启动时该字段自动加载到内存中。新加模块sys.modules会自动记录该模块,第二次导入时直接从字典中加载,加快运行速度。他拥有字典的一切方法。
keys是模块名
values是模块
modules返回路径
5、sys.stdin/sys.stdout/sys.stderr
Python程序的标准输入/输出/出错流定义在sys模块中,分别 为: sys.stdin, sys.stdout, sys.stderr
示例
import sys
print('Pleanse enter your name:')
name=sys.stdin.readline()[:-1] # 写入?应该是读取
sys.stdout.write('Hi, %s' % name)
输出
import sys
for f in (sys.stdin, sys.stdout, sys.stderr):
print(f)
输出
<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
可以看出stdin, stdout, stderr在Python中无非都是文件属性的对象,他们在Python启动时自动与Shell 环境中的标准输入,输出,出错关联。
而Python程序的在Shell中的I/O重定向与DOS命令的重定向完全相同,其实这种重定向是由Shell来提供的,与Python 本身并无关系。于是我们可以在Python程序内部将stdin,stdout,stderr读写操作重定向到一个内部对象,Python提供了一个StringIO模块来完成这个设想。
import sys
from io import StringIO
import sys
buff =StringIO()
temp = sys.stdout #保存标准I/O流
sys.stdout = buff #将标准I/O流重定向到buff对象
print(42, 'hello', 0.001)
sys.stdout =temp #恢复标准I/O流
print(buff.getvalue())