【问题标题】:How to stop the execution of an imported python script without exiting the python altogether?如何在不完全退出 python 的情况下停止执行导入的 python 脚本?
【发布时间】:2022-11-12 04:15:57
【问题描述】:

在下面的示例中,当我运行y_file.py 时,我需要打印5 而不打印Hello。 如何在不完全退出 python 的情况下停止执行导入的 python 脚本x_file.pysys.exit() 似乎完全退出了 python。

x_file.py

import sys
x = 5
if __name__ != '__main__':
  # stop executing x.py, but do not exit python
  # sys.exit() # this line exits python
print("Hello")

y_file.py

import x_file
print(x_file.x)

【问题讨论】:

  • 为什么不将 print("Hello") 放在 if __name__ == "__main__" 内?
  • @jvx8ss 因为 IRL 不止一行,我不想在这么多行上有差异。另外,学术兴趣:)

标签: python


【解决方案1】:

正如jvx8ss 建议的那样,您可以通过将打印放在if __name__ == "__main__": 条件中来解决此问题。注意等式“==”而不是不等式“!=”。 最终代码:

import sys
x = 5
if __name__ == "__main__":
    # stop executing x.py, but do not exit python
    # sys.exit() # this line exits python
    print("Hello")

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2014-12-10
    • 2020-03-31
    • 2011-06-26
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多