【问题标题】:Python: Running a strip of code unless importedPython:除非导入,否则运行一段代码
【发布时间】:2013-07-12 10:49:38
【问题描述】:

我有一个文件要导入到我的程序中(比如一个带有字典的文件)。在这个文件的开头,我想放一段代码,打印出这不是主文件,然后是exit()。我发现的问题是,这段代码是在导入我不想发生的字典模块时运行的。如何防止这种情况?

我试过了,但它不起作用:

if not Main_file:
    print('These aren\'t the droids you\'re looking for')
    exit()

在主文件中,导入前当然会有Main_file = True

【问题讨论】:

标签: python import python-import


【解决方案1】:

您可以使用__name__ 特殊变量来检查您的模块是否被用作主模块:

if __name__ == '__main__':
    print('These aren\'t the droids you\'re looking for')
    exit()

【讨论】:

  • 打印参数不是字符串
  • @GrijeshChauhan - 没有检查,只是从 OP 复制的 :)
【解决方案2】:

if __name__ == '__main__'可以识别这是否是主文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多