【问题标题】:Fix duplicate outputs修复重复输出
【发布时间】:2021-06-01 03:55:41
【问题描述】:

我正在尝试运行此代码,一切似乎都很顺利,但是,输出重复,我不知道为什么。当我删除对“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

【问题讨论】:

  • 它在我的机器上完美运行。
  • 提供的代码无法产生输出。有四个打印语句,但输出有八行。

标签: python import duplicates output


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这里发生的事情是当您包含检查“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

    【讨论】:

      【解决方案3】:

      好的

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-12
        • 1970-01-01
        • 2018-11-06
        相关资源
        最近更新 更多