sys模块提供了一系列有关Python运行环境的变量和函数,包括解释器的一些变量,与解释器交互的函数,比较常用到的就是命令行参数。
先看一个python实现more的例子, 这个例子接受命令行参数,输入一个文件,每次显示10行,如果没有输出完成则显示more并且接受Y/y的输入,决定是否继续显示下面的内容。
more.py 来自<<programming python>>,作者略修改为python3版本
sys.stdout 标准输出,这个例子先备份标准,然后把标准输出到文件,然后输出一段字符串,再恢复到console。
>>> import sys
>>> f = open('log.txt', 'a')
>>> __console__ = sys.stdout
>>> sys.stdout = f
>>> print('hello world')
>>> sys.stdout = __console__
>>> print('hello world')
hello world
sys.stdin 标准输入,等价于input()。
>>> import sys
>>> input_string = sys.stdin.readline()
i like python
>>> print('输出', input_string)
输出 i like python
上面介绍了sys模块比较常用的三个方法,以上例子在python3.6上面调试通过,读者自行花10分钟上机调试一下,加强记忆,其他函数建议在使用的时候翻查手册。
联系客服