【问题标题】:Imported function is being executed twice导入的函数正在执行两次
【发布时间】:2025-12-11 23:05:02
【问题描述】:

当我将一个函数从一个模块导入到另一个文件的脚本中然后运行它时,该函数在它完成后重新开始,尽管它应该只运行一次。

但是,如果我只使用导入的函数运行单元格,那么该函数有时只运行一次,这令人困惑,因为我已停用脚本中的所有其他内容,所以它不应该有所作为,不是吗?但有时它也会运行两次,这更加令人困惑,因为在此期间我没有更改任何内容(至少我不会知道)。

一个区别是,当我运行整个脚本时,控制台会显示

Reloaded modules: mytestmodule

脚本执行后,当我只运行单元格时,这不会显示。不过我不知道这是否重要。

不管怎样,这里是函数(来自文件 mytestmodule.py):

def equation():
    
    print("Hi! Please enter your name.")
    name=input()
    
    print("Hello "+name+"! Please enter an integer that is bigger than 1 but smaller than 10.")
    
    answertrue="That is correct!"
    answerfalse="That integer is not correct. Please try again."
    answernointeger="That is not an integer. Please try again."

    biggersmaller=True
    while biggersmaller:
        task=input()
        try:
            if int(task)>1 and int(task)<10:
                return(print(answertrue))
                break
            else:
                print(answerfalse)
        except ValueError:
            print(answernointeger)
equation()

这是另一个文件中的导入脚本:

import mytestmodule
mytestmodule.equation()

【问题讨论】:

  • 当你导入一个模块时,基础层的所有东西都会被执行。您可以在此致电equationimport 后面还有一个,所以它会被调用两次。
  • @Brian 谢谢你,成功了!编辑:这也是一些快速的答案,哇!

标签: python function import


【解决方案1】:

这是因为在您的 mytestmodule.py 内部,您已经在调用 equation 函数。 要么:

  1. mytestmodule.py中删除equation的调用
  1. 导入后不要调用函数

【讨论】:

  • 或 3. 将 if __name__ == "__main__": 放在模块中的调用之前,以便在导入时不会运行。
  • @MarkRansom 谢谢,成功了!编辑:这也是一些快速的答案,哇!