sys 模块:程序运行时的处理

sys 模块:程序运行时的处理

1. 处理命令行参数

在解释器启动后, argv 列表包含了传递给脚本的所有参数.列表的第一个元素为脚本自身的名称.

使用sys模块获得脚本的参数
import sys
print "script name is", sys.argv[0]
if len(sys.argv) > 1:
    print "there are", len(sys.argv)-1, "arguments:"
    for arg in sys.argv[1:]:
        print arg
else:
    print "there are no arguments!"

2. 模块位置

使用sys模块操作模块搜索路径:path
import sys
print "path has", len(sys.path), "members"
# add the sample directory to the path
sys.path.insert(0, "samples")
import sample


使用sys模块查找内建模块:builtin_module_names
def dump(module):
    print module, "=>",
    if module in sys.builtin_module_names:
        print "<BUILTIN>"
    else:
        module = _ _import_ _(module)
        print module._ _file_ _
dump("os")  #C:/python/lib/os.pyc
dump("sys")  #<BUILTIN>

使用sys模块查找已导入的模块:sys.modules.keys()
print sys.modules.keys()#['os.path', 'os', 'exceptions', '_ _main_ _','sys', '_ _builtin_ _']

3. 处理引用记数

getrefcount 函数返回给定对象的引用记数 -也就是这个对象使用次数. Python会跟踪这个值,当它减少为0的时候,就销毁这个对象.注意这个值总是比实际的数量大,因为该函数本身在确定这个值的时候依赖这个对象.

使用sys模块获得引用记数:sys.getrefcount
variable = 1234
print sys.getrefcount(0)   #50
print sys.getrefcount(variable)  #3
print sys.getrefcount(None)   #192

注释:典型的平台有Windows9X/NT(显示为 win32 ),以及Macintosh(显示为 mac ) . 对于 Unix 系统而言,platform 通常来自"uname-r"命令的输出,例如 irix6 ,linux2 ,或者 sunos5 (Solaris).

使用sys模块获得当前平台:sys.platform
if sys.platform == "win32":
    import ntpath
    pathmodule = ntpath
elif sys.platform == "mac":
    import macpath
    pathmodule = macpath
else:
    # assume it's a posix platform
    import posixpath
    pathmodule = posixpath
print pathmodule

4. 跟踪程序:调试利器

setprofiler 函数在关键步骤有跟踪;settrace 函数在每一步有跟踪。基于setprofiler 函数, profile模块提供了一个完整的分析器框架.基于settrace 函数提供的跟踪功能, pdb 模块提供了完整的调试( debug )框架.

setprofiler 函数允许你配置一个分析函数(profilingfunction).这个函数会在每次调用某个函数或方法时被调用(明确或隐含的),或是遇到异常的时候被调用.

使用sys模块配置分析函数:setprofile
def test(n):
    j = 0
    for i in range(n):
        j = j + i
    return n
def profiler(frame, event, arg):
 print event, frame.f_code.co_name, frame.f_lineno, "->", arg
# profiler is activated on the next call, return, or exception
# 分析函数将在下次函数调用, 返回, 或异常时激活
sys.setprofile(profiler)
# profile this function call
# 分析这次函数调用
test(1)
# disable profiler
# 禁用分析函数
sys.setprofile(None)
# don't profile this call
# 不会分析这次函数调用
test(2)

call test 3 -> None
return test 7 -> 1
 

settrace 函数与此类似,但是 trace 函数会在解释器每执行到新的一行时被调用.

使用sys模块配置单步跟踪函数:trace
def test(n):
    j = 0
    for i in range(n):
        j = j + i
    return n
def tracer(frame, event, arg):
    print event, frame.f_code.co_name, frame.f_lineno, "->", arg
    return tracer
# tracer is activated on the next call, return, or exception
# 跟踪器将在下次函数调用, 返回, 或异常时激活
sys.settrace(tracer)
# trace this function call
# 跟踪这次函数调用
test(1)
# disable tracing
# 禁用跟踪器
sys.settrace(None)
# don't trace this call
# 不会跟踪这次函数调用
test(2)

call test 3 -> None
line test 4 -> None
line test 5 -> None
line test 6 -> None
line test 7 -> None
return test 7 -> 1
 

5. 处理标准输出/输入

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

使用sys重定向输出
import sys
import string
class Redirect:
    def _ _init_ _(self, stdout):
        self.stdout = stdout
    def write(self, s):
        self.stdout.write(string.lower(s))
# redirect standard output (including the print statement)
# 重定向标准输出(包括print语句)
old_stdout = sys.stdout
sys.stdout = Redirect(sys.stdout)
print "HEJA SVERIGE",
print "FRISKT HUM/303/226R"
# restore standard output
# 恢复标准输出
sys.stdout = old_stdout

print "M/303/205/303/205/303/205/303/205L!"
heja sverige friskt hum/303/266r
M/303/205/303/205/303/205/303/205L!
 

6. 退出程序的钩子函数

执行至主程序的末尾时,解释器会自动退出.但是如果需要中途退出程序,可以调用 sys.exit .

使用sys模块退出程序:sys.exit
import sys
print "hello"
sys.exit(1)
print "there"

hello

注意 sys.exit 并不是立即退出.而是引发一个 SystemExit 异常.这意味着你可以在主程序中捕获对 sys.exit 的调用.

捕获sys.exit调用:SystemExit异常
import sys
print "hello"
try:
    sys.exit(1)
except SystemExit:
    pass
print "there"

hello
there

如果准备在退出前自己清理一些东西(比如删除临时文件),你可以配置一个 "退出处理函数"(exithandler),它将在程序退出的时候自动被调用. Python2.0以后, 你可以使用 atexit 模块来注册多个退出处理函数.

另一种捕获sys.exit调用的方法:sys.exitfunc
def exitfunc():
    print "world"
sys.exitfunc = exitfunc
print "hello"
sys.exit(1)
print "there" # never printed # 不会被 print

hello

world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值