【问题标题】:if __name__ == "__main__" on Imports如果 __name__ == "__main__" 在导入
【发布时间】:2018-03-13 15:48:06
【问题描述】:

我正在处理两个 python 文件。完成后,我打算从另一个人那里打电话:

main.py
import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
import subfile
# A long body of codes that does things

subfile.py
import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
# Another long body of codes that does things

如果我调用 main.py,我希望它也能运行 subfile.py。偶尔,我会单独运行subfile.py,并希望它自己正常运行。现在,在subfile.py 中,我应该将导入命令嵌套在if __name__ == "__main__" 下吗?

subfile.py
if __name__ == "__main__": 
    import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
# Another long body of codes that does things

【问题讨论】:

    标签: python import nested main


    【解决方案1】:

    如果您的动机是避免多次导入同一个模块,请不要害怕。

    已经导入的模块的导入几乎是无操作的,基本上只是在模块的字典中查找。

    所以没有任何好处,只是使程序更复杂,可读性更差。

    【讨论】:

      【解决方案2】:

      不,作为一般规则,将您的导入放在文件的顶部,并让 python 管理它。在某些情况下,导入应该放在类/方法/函数中,但这不是其中之一。

      如果事情变得更复杂,您可以将导入放在包的 __init__.py 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-13
        • 2021-08-25
        • 2020-06-05
        • 2015-09-12
        • 2017-07-03
        • 1970-01-01
        • 2023-03-19
        • 2013-12-11
        相关资源
        最近更新 更多