码迷,mamicode.com
首页 > 其他好文 > 详细

Executing modules as scripts

时间:2016-10-21 13:08:35      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:script   for   add   util   this   exec   ace   utils   comm   

When you run a Python module with

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo.py 50
1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:

>>>
>>> import fibo
>>>

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

Executing modules as scripts

标签:script   for   add   util   this   exec   ace   utils   comm   

原文地址:http://www.cnblogs.com/dltts/p/5984212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!