繁体   English   中英

找出试图在一个模块python中使用导入的模块名称

[英]Figure out the module name trying to use imports in one module python

我试图找出是否有一种方法可以检测正在尝试从模块中导入内容的模块的名称,例如,我有一个名为“ all_modules”的模块,该模块将我需要的所有导入存储在整个文件夹中并认为将其导入文件比在我所有文件中多次导入要容易得多,但是通过这样做,我注意到一旦遇到导入本身,它将停止尝试导入模块。 例如,这是我这样做的总体思路是:

   #all_modules.py
   import sys, os, time, threading, re, random, urllib.request, urllib.parse
   import a, b, c, d # fake modules but general idea is here
   # any modules you would need throughout the folder really this is just a small example

   #a.py 
   from all_modules import * 
   print(sys.version_info) # works fine but lets do the last module

   #c.py
   from all_modules import *
   and_one_more.someFunction("Hello, World!") # it didn't import it because it stopped when it tried to import itself

所以我的想法是找出试图访问导入的文件名,然后执行此操作

  #all_modules.py - Example two
  module_list = ["sys", "os", "time", "threading", "re", "random", "urllib", "urllib.request", "urllib.parse", "a", "b", "c"]
  for module in module_list:
      if file_name == module: continue # this is what I do not know how to do and not sure if it is even possible, but it's the only solution I have to be able to try to do what I am doing 

      globals()[module] = __import__(module)

我想知道是否有一些解决方法可以阻止这种情况,还是我必须在每个文件中导入我在整个文件中使用的所有模块? 就目前而言,我遇到了另一个问题,即没有导入其他模块的错误,因为在遇到其他模块之后它没有导入其余模块,所以我想知道我想做的事情是否可行,或者解决该问题的方法是否很好,还是我必须在整个文件中单独导入模块?

如何从imp模块使用load_module方法:

#!/usr/bin/python

import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):

    try:
        return sys.modules[name]
    except KeyError:
        pass

    fp, pathname, description = imp.find_module(name)
    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        if fp:
            fp.close()

module_list = ["sys", "os",
               "time", "threading",
               "re",
               "urllib" ]

for module in module_list:
    module = __import__(module)
    print module

输出:

 <module 'sys' (built-in)>
 <module 'os' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.pyc'>
 <module 'time' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/time.so'>
 <module 'threading' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.pyc'>
 <module 're' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.pyc'>
 <module 'urllib' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.pyc'>

您面临的问题是经典的周期性导入问题。 在python中,解决此问题的最简单方法是根本不做您正在做的事情,如果您绝对有2个相互依赖的模块,则可以将模块作为名称空间导入,而不必导入其中定义的所有内容(即import x vs from x import * )。

通常,*导入在python中不受欢迎,因为其他人不清楚您的代码中定义了什么的其他人。 基本上是在破坏名称空间的目的。

您应该真正阅读PEP8 如果您打算将代码发布到世界上,那么这应该是一个样式指南。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM