python系统自带模块sys,包含许多和系统相关的字段和方法。常用的如下:
一、sys.platform 显示当前操作系统
二、sys.argv 显示当前文件路径及文件名
sys.argv[]使用来获取命令行参数的,sys.argv[0]表示当前文件路径和文件名,从sys.argv[1]开始,是获取的命令行参数。
三、sys.path 系统环境变量Path列表
import sys # 显示当前操作系统,Windows、linux等 ret = sys.platform print(ret,type(ret)) # win32 <class 'str'> # 当前文件路径及文件名 ret = sys.argv print(ret,type(ret)) # ['D:/pycharm/dongxuew/hello_world.py'] <class 'list'> # 系统环境变量列表 ret = sys.path for i in ret:print(i)
四、sys.exit() 结束程序,抛出SystemExit异常
SystemExit是唯一不会当做错误的异常,此异常被捕获到后,可进行一些清理操作再退出程序;否则,直接退出。
# 当程序捕获到SystemExit异常:可进行后续清理操作,再退出。 import sys if __name__ == '__main__': try: sys.exit('GoodBye!!!') except SystemExit as e: print('the information of SystemExit:{}'.format(e)) print('the program doesnot exit.') print('now,the game is over!') # 当程序没有捕获到SystemExit异常,直接退出。 if __name__ == '__main__': try: sys.exit('GoodBye!!!') except Exception as e: print('the information of SystemExit:{}'.format(e)) print('the program doesnot exit.') print('now,the game is over!') # output:GoodBye!!!
五、sys.stdin()、sys.stdout()、sys.stderr() 读写重定向
# 重定向读写sys.stdin()、sys.stdout()、sys.stderr() # 都是文件属性的对象,在程序中,与出输入、输出、出错有关。 for i in (sys.stdin,sys.stdout,sys.stderr): print(i) # <_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'> print('what is r name?') # print后台实际调用的是sys.stdout.write(obj+'\n') name = sys.stdin.readline()[:-1] sys.stdout.write('r name is {}'.format(name)) # sys.stdout.flush() 输出刷新,与缓冲区保持一致 # 进度条效果显示 import time import sys for i in range(101): time.sleep(0.1) sys.stdout.write('#') sys.stdout.flush() if i % 10 == 0 and i != 0 : sys.stdout.write(str(i))
浙公网安备 33010602011771号