python - 导入的函数正在执行两次
问题描述
当我将一个模块中的函数导入另一个文件的脚本然后运行它时,该函数在完成后重新开始,尽管它应该只运行一次。
但是,如果我只使用导入的函数运行单元格,那么该函数有时只运行一次,这会令人困惑,因为我已经停用了脚本中的所有其他内容,所以它不应该有所作为,不是吗?但有时它也会运行两次,这更加令人困惑,因为在此期间我没有改变任何东西(至少我不会知道)。
一个区别是,当我运行整个脚本时,控制台会说
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()
解决方案
这是因为在您的内部您已经mytestmodule.py
在调用该equation
函数。任何一个:
- 删除
equation
from的调用mytestmodule.py
- 或者
- 导入后不要调用函数
推荐阅读
- google-maps - Flutter Google Map 在 IOS 中首次打开时崩溃
- python - 知道如何在 python 中修复此错误“TypeError: unsupported operand type(s) for -: 'list' and 'list'”吗?
- python - django.core.exceptions.ImproperlyConfigured: 。您必须定义环境变量 DJANGO_SETTINGS_MODULE
- python - 需要一个正则表达式来捕获python文件中的所有输入函数
- hlsl - 着色语言中内置函数的精度是多少?
- javascript - 如何调整网站“横幅”的大小以适应不同大小的窗口?
- c# - WasapiLoopbackCapture 内部音频识别在没有音频时会产生乱码和文本
- notifications - Exchange Web 服务:重新连接流时,流通知消息是否会丢失?
- python - 由于 Pandas 单个单元格中的多个字符串导致的日期时间转换错误
- spring-boot - 如何在 Ribbon 和 FeignClient 中临时禁用 Eureka Server 支持