【问题标题】:Why does importing a variable from another python file run all code in that file? [duplicate]为什么从另一个 python 文件导入变量会运行该文件中的所有代码? [复制]
【发布时间】:2019-07-03 06:29:48
【问题描述】:

我有一个名为 test1.py 的文件,代码如下:

print("HELLO WORLD")
x=999

我有另一个名为 test2.py 的文件,代码如下:

from test1 import x

print(x,"hello!")

为什么是这样的输出:

HELLO WORLD
999 hello!

为什么它在 test1 中执行函数,而不是让我得到变量 x

在 test.py 我试过了:

from test1 import x as a
print(a,"hello!")

这让我得到相同的输出。

预期结果:

999 hello!

实际结果:

HELLO WORLD
999 hello!

抱歉,如果这是一个重复的问题 - 我只是找不到解决方案。 编辑:这在之前被标记为重复 - 一个问题:使用if __name__ == "__main__" 逻辑阻止我访问 main 中的任何变量。我只想要一个变量而不运行文件。

【问题讨论】:

  • 我们能看到更多你的代码吗,你是怎么导入的?
  • 这就是所有的代码——我在这里没有做任何花哨的事情,我只是想将 x 的值放入 test2.py 而不运行 test1.py 中的代码
  • 在 test1.py 中,您应该在单独的函数中拥有 x。然后导入x 看起来像from test1 import function。编写函数,使其返回xx 现在将成为 test1 的一个属性
  • 是的,解决了 - 谢谢!

标签: python python-3.x python-import


【解决方案1】:

模块在导入时执行。如果模块包含您不想在导入时执行的代码,您可以使用 if-block ìf __name__ == "__main__" 包装此代码。

http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm (发现于Why is Python running my module when I import it, and how do I stop it? )

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 2021-06-22
    相关资源
    最近更新 更多