how do I determine whether a python script is imported as module or run as script?

后端 未结 2 750
春和景丽
春和景丽 2020-12-15 16:25

The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? I

2条回答
  •  有刺的猬
    2020-12-15 17:04

    from python docs:

    When you run a Python module with

    python fibo.py

    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__':
        # Running as a script
    

    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

提交回复
热议问题