我有一个要导入程序的文件(例如带有字典的文件)。在此文件的开头,我想放一段代码,打印出该文件不是主文件,然后输出exit()
。我发现的问题是此代码是在导入我不想发生的字典模块上运行的。如何预防呢?
我尝试了这个,但是不起作用:
if not Main_file:
print('These aren\'t the droids you\'re looking for')
exit()
在主文件中,当然会Main_file = True
在导入之前。
您可以使用__name__
特殊变量来检查您的模块是否用作主模块:
if __name__ == '__main__':
print('These aren\'t the droids you\'re looking for')
exit()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句