Python常用模块之sys

sys模块提供了一系列有关Python运行环境的变量和函数。

常见用法

  • sys.argv
    可以用sys.argv获取当前正在执行的命令行参数的参数列表(list)。
变量解释
sys.argv[0] 当前程序名
sys.argv[1] 第一个参数
sys.argv[0] 第二个参数

参考代码:

# encoding: utf-8
# filename: argv_test.py
import sys

# 获取脚本名字
print 'The name of this program is: %s' %(sys.argv[0])
# 获取参数列表
print 'The command line arguments are:'
for i in sys.argv:
    print i
# 统计参数个数
print 'There are %s arguments.'%(len(sys.argv)-1)

运行结果:

E:p>python argv_test.py arg1 arg2 arg3
The name of this program is: argv_test.py
The command line arguments are:
argv_test.py
arg1
arg2
arg3
There are 3 arguments.
  • sys.platform

获取当前执行环境的平台,如win32表示是Windows 32bit操作系统,linux2表示是linux平台;

# linux 
>>> import sys
>>> sys.platform
'linux2'

# windows
>>> import sys
>>> sys.platform
'win32'
  • sys.path

path是一个目录列表,供Python从中查找第三方扩展模块。在python启动时,sys.path根据内建规则、PYTHONPATH变量进行初始化。

>>> sys.path
['', 'E:\Python27\Lib\idlelib', 'C:\Windows\system32\python27.zip', 'E:\Python27\DLLs', 'E:\Python27\lib', 'E:\Python27\lib\plat-win', 'E:\Python27\lib\lib-tk', 'E:\Python27', 'E:\Python27\lib\site-packages']

有时候为了让python能够找到我们自己定义的模块,需要修改sys.path的内容,比如:

# 在path的开始位置 插入test
>>> sys.path.insert(0,'test')
>>> sys.path
['test', '', 'E:\Python27\Lib\idlelib', 'C:\Windows\system32\python27.zip', 'E:\Python27\DLLs', 'E:\Python27\lib', 'E:\Python27\lib\plat-win', 'E:\Python27\lib\lib-tk', 'E:\Python27', 'E:\Python27\lib\site-packages']
# 可以成功import test
>>> import test
# 找不到 other 这个模块
>>> import other
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    import other
ImportError: No module named other
# 需要添加path
>>> sys.path.insert(0,'other')
>>> import other

也可以用sys.path.append(“mine module path”)来添加自定义的module。

  • sys.builtin_module_names

sys.builtin_module_names返回一个列表,包含内建模块的名字。如:

>>> import sys
>>> print sys.builtin_module_names
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022', '_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_csv', '_functools', '_heapq', '_hotshot', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_random', '_sha', '_sha256', '_sha512', '_sre', '_struct', '_subprocess', '_symtable', '_warnings', '_weakref', '_winreg', 'array', 'audioop', 'binascii', 'cPickle', 'cStringIO', 'cmath', 'datetime', 'errno', 'exceptions', 'future_builtins', 'gc', 'imageop', 'imp', 'itertools', 'marshal', 'math', 'mmap', 'msvcrt', 'nt', 'operator', 'parser', 'signal', 'strop', 'sys', 'thread', 'time', 'xxsubtype', 'zipimport', 'zlib')

代码示例:

# encoding: utf-8
# find_module.py

import sys

# print sys.builtin_module_names

def find_module(module):
    if module in sys.builtin_module_names:
        print module," => ","__builtin__"
    else:
        print module,"=> ",__import__(module).__file__


find_module('os')
find_module('sys')
find_module('strop')
find_module('zlib')
find_module('string')

# 运行结果:
>>> 
======================== RESTART: E:/p/find_module.py ========================
os =>  E:Python27libos.pyc
sys  =>  __builtin__
strop  =>  __builtin__
zlib  =>  __builtin__
string =>  E:Python27libstring.pyc
  • sys.exit(n)

调用sys.exit(n)可以中途退出程序,当参数非0时,会引发一个SystemExit异常,从而可以在主程序中捕获该异常。
看代码:

# encoding: utf-8
import sys

print 'running...'

try:
    sys.exit(1)
except SystemExit:
    print 'SystemExit exit 1'

print 'exited'

运行结果:

>>> 
======================= RESTART: E:/p/sys_exit_test.py =======================
running...
SystemExit exit 1
exited

 

常用方法:

1、 通过sys模块获取程序参数

import sys

def usage():
    '''usage'''
    print 'Usage: %s %s %s %s' % (sys.argv[0], 'tokenid', 'Subject', 'Content')
    sys.exit()

def main():
    if len(sys.argv) != 4:
        usage()
    else:
        print(sys.argv[0])
        print(sys.argv[1])
        print(sys.argv[2])
        print(sys.argv[3])

if __name__ == "__main__":
    main()

运行脚本:

D:Pythonmodules>python os_modules.py
Usage: os_modules.py tokenid Subject Content

D:Pythonmodules>python os_modules.py aa bb cc
os_modules.py
aa
bb
cc

python的sys模块默认是把第一个参数默认是程序本省,从第二个参数起都是代码后面跟着的参数,通过sys.arg[n]就可以获得传入到程序中的参数


 

常用方法:

sys.stdinstdoutstderr

功能:stdin , stdout , 以及stderr 变量包含与标准I/O 流对应的流对象. 如果需要更好地控制输出,而print 不能满足你的要求, 它们就是你所需要的. 你也可以替换它们, 这时候你就可以重定向输出和输入到其它设备( device ), 或者以非标准的方式处理它们

sys.stdout 与print

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了sys.stdout.write(obj+' '),print 将你需要的内容打印到了控制台,然后追加了一个换行符,print 会调用 sys.stdout 的 write 方法 以下两行在事实上等价


import sys
sys.stdout.write("hello")
print('hello')

# hellohello

import sys
sys.stdout.write("hello 
")
print('hello')

# hello 
# hello

sys.stdin 与 raw_input

import sys
a = raw_input('raw_input_name: ')
print(a)
print 'stdin_name: ',
b = sys.stdin.readline()
print(b)

# raw_input_name: ;LIJUNJIANG
# ;LIJUNJIANG
# stdin_name: AAAA
# AAAA

从控制台重定向到文件

Import sys
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'

# 在当前文件下新生成一个文件out.log,文件内容为hello, 

捕获sys.exit(n)调用

功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)

def exitfunc():
    print "hello world"
sys.exitfunc = exitfunc  # 设置捕获时调用的函数
print "This exit test"
sys.exit(1)     # 退出自动调用exitfunc()后,程序依然退出了
print "there"  # 不会被 print
结果:
This exit test
hello world

exitfunc()函数,及当执行sys.exit(1)的时候,调用exitfunc()函数 sys.exit(1)后面的内容就不会执行了,因为程序已经退出

原文地址:https://www.cnblogs.com/zknublx/p/8464423.html