修复重复输出

时间:2021-06-01 03:55:41

标签: python import duplicates output

我正在尝试运行此代码,一切似乎进展顺利,但是,输出重复,我不知道为什么。当我删除对“main”(我正在处理的文件)的检查时,它没有同样的问题,只返回一次输出

def file_exists(name):
  try:
    exec("import " + name) 
    return True 
  except ModuleNotFoundError:
    return False

#test
print(file_exists("main")) # -> True (file being worked in)
print(file_exists("module1")) # -> True (module exists in program)
print(file_exists("math")) # -> True
print(file_exists("english")) # -> False

duplicate outputs

3 个答案:

答案 0 :(得分:1)

我的粗略想法是,一旦main运行,它会运行所有导入语句,然后使用exec再次运行导入,由于相同模块名称的双重导入,后续导入失败。我会打印看到的异常 - 包括类型和消息。

答案 1 :(得分:0)

这里发生的事情是当您检查“main”时

程序在运行时运行“import main”并再次初始化主模块

即类似下面的东西

def file_exists(name):
try:
    exec("import " + name) 
    return True # return true for initial call,#5. True
except ModuleNotFoundError:
    return False

#test
print(file_exists("main")) # -> True (file being worked in), this imports the module and initialises it as its not found in sys.modules

"""
def file_exists(name):
   try:
       exec("import " + name) - #a duplicate import so executes and moves to next line
       return True #returns true
   except ModuleNotFoundError:
       return False

   #test
   print(file_exists("main")) #1. True
   print(file_exists("module1")) # -> True (module exists in program), 2.True
   print(file_exists("math")) # -> True, 3.True
   print(file_exists("english")) # 4. False
"""

# after 4th print the control goes back to the check which call the import that will print from (5)
print(file_exists("module1")) # -> True (module exists in program), 6. True
print(file_exists("math")) # -> True, 7.True
print(file_exists("english")) # -> False` 8. True

但是如果我们移除 main 的检查,以上都不会发生,并且只执行 4 个检查和一个打印语句,因此只有 4 行打印。

参考 - https://docs.python.org/2/reference/simple_stmts.html#the-import-statement

答案 2 :(得分:0)

好的

1-这段代码运行过多的问题是,当你导入main文件时,会导致主文件运行两次。

2-第二个问题是module1函数是main文件的一部分,必须以这种方式导入。

from main import module1

看看这个

def module1():
    pass

def file_exists(name):
  try:
    exec(f"import {name}")
    return name, True
  except:
      try:
        exec(f"from main import {name}")
        return name, True
      except Exception:
        return name, False

files=["main", "module1", "math", "english"]
for f in files:
    print(file_exists(f))
相关问题