如果导入时uuu name uuuuu==“uuuu main”

2024-05-06 11:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理两个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

如果我打电话主.py,我希望它也能运行subfile.py。偶尔,我会单独运行subfile.py,并希望它自己正常运行。现在,在subfile.py中,我应该将import命令嵌套在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

Tags: pyimportredatetimetimeosmainlogging
2条回答

如果你的动机是避免多次导入同一个模块,不要害怕。你知道吗

导入已经导入的模块几乎是不可操作的,基本上只是模块目录中的一个查找。你知道吗

因此没有任何好处,只是让程序变得更复杂、可读性更低的缺点。你知道吗

不,一般来说,将导入放在文件的顶部,并让python管理它。在某些情况下,导入应该放在类/方法/函数中,但这不是其中之一。你知道吗

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

相关问题 更多 >