if __name__ == "__main__" 导入
if __name__ == "__main__" on Imports
我正在处理两个 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 管理它。在某些情况下,导入应该放在 class/method/function 内,但这不是其中之一。
如果事情变得更复杂,您可以将导入放在包的 __init__.py
中。
如果您的动机是避免多次导入同一个模块,请不要害怕。
导入一个已经导入的模块几乎是空操作,基本上只是在模块字典中查找一次。
所以没有好处,只是让程序变得更复杂和可读性更差的缺点。
我正在处理两个 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 管理它。在某些情况下,导入应该放在 class/method/function 内,但这不是其中之一。
如果事情变得更复杂,您可以将导入放在包的 __init__.py
中。
如果您的动机是避免多次导入同一个模块,请不要害怕。
导入一个已经导入的模块几乎是空操作,基本上只是在模块字典中查找一次。
所以没有好处,只是让程序变得更复杂和可读性更差的缺点。