首页 > 解决方案 > 导入的函数正在执行两次

问题描述

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

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

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

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()

标签: pythonfunctionimport

解决方案


这是因为在您的内部您已经mytestmodule.py在调用该equation函数。任何一个:

  1. 删除equationfrom的调用mytestmodule.py
  • 或者
  1. 导入后不要调用函数

推荐阅读