sys模块提供了关于python解释器的一些常量和函数。使用dir(sys)列出其中的常量和方法,help(sys)查看详细帮助信息。
例如:查看和设置递归深度限制:
1 2 3 4 5 6 7 8 9 |
Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.getrecursionlimit() 1000 >>> sys.setrecursionlimit(800) >>> sys.getrecursionlimit() 800 |
查看Python版本信息
1 2 3 4 5 |
>>> import sys >>> sys.version '2.7.6 (default, Jun 22 2015, 17:58:13) n[GCC 4.8.2]' >>> sys.version_info sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0) |
命令行参数
有些应用需要往脚本里传入参数,这就用到了sys.argv。sys.argv包含了传入到脚本里的参数:列表里第一元素是脚本本身,然后依次为参数。例如有脚本argv_test.py如下:
1 2 3 4 5 6 7 8 9 10 11 |
import sys // 输出命令行参数 print sys.argv // 遍历命令行参数 for i in range(len(sys.argv)): if i == 0: print "Function name: %s" % sys.argv[0] else: print "%d argument: %s" % (i, sys.argv[i]) |
改变Python交互模式的输出方式
Python的交互模式使它和perl和java比起来更易使用和学习。有些用户也许需要不同的输出方式,简单示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> import sys >>> x = 66 >>> x 66 # 默认输出 >>> import sys >>> def my_print(x): ... print "display: ", ... print x ... >>> sys.displayhook = my_print # 自定义输出 >>> x display: 66 # 可以看到这里调用了my_print函数 >>> print x # print 行为未变 66 >>> |
标准输入输出流
使用Linux系统的都知道标准输入输出流。例如,标准输入(stdin)、标准输出(stdout)、标准错误输出(stderr),它们也被叫做管道(pipe)。
标准输入通常连接键盘,标准输出和标准错误输出通常连接终端。这些流可以用sys模块中的对象表示:
1 2 3 4 5 6 7 8 |
>>> import sys >>> for i in (sys.stdin, sys.stdout, sys.stderr): ... print(i) ... <open file '<stdin>', mode 'r' at 0x7f52521570c0> <open file '<stdout>', mode 'w' at 0x7f5252157150> <open file '<stderr>', mode 'w' at 0x7f52521571e0> >>> |
下面是使用标准流的例子:
1 2 3 4 5 6 7 8 9 10 11 12 |
import sys while True: try: number = raw_input("input: ") except EOFError: break number = int(number) if number == 0: print >> sys.stderr, "can't divide 0" else: print 1.0/number |
一般使用:
1 2 3 4 5 |
tian@tian-VirtualBox:~/Documents/blog/python$ python stream.py input: 4 0.25 input: 5 0.2 |
使用流(重定向):
1 |
python stream.py < number.txt # number.txt 文件一行一个数字 |
我们也可以用如下命令把输出重定向到文件中:
1 |
python stream.py < number.txt > output.txt |
其他
大端小端:
1 2 |
>>> sys.byteorder 'little' |
Python路径:
1 2 |
>>> sys.executable '/usr/bin/python' |
支持的最大整数:
1 2 |
>>> sys.maxint 9223372036854775807 |
已经加载的模块:
1 |
>>> sys.modules |
Python的模块查找路径:
1 2 |
>>> sys.path ['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] |
查看平台:
1 2 |
>>> sys.platform 'linux2' |