Executing modules as scripts

Posted 通天树

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Executing modules as scripts相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

HTTP/2 服务器推送导致重复请求

AS中多个module引入V4包重复,要怎么解决

Django【import MySQLdb as Database ModuleNotFoundError: No module named ‘MySQLdb‘】

Android Studio中的Module是指啥

As 启动项目出现unsupported modules detected

As 启动项目出现unsupported modules detected