[英]Toggle between relative and absolute Import of built in module
So I have the script that imports the standard module checkmarc. 所以我有导入标准模块checkmarc的脚本。
import checkdmarc
I want to implement some mock checkmarc that will seat at the same directory as the script. 我想实现一些模拟checkmarc,它将与脚本位于同一目录。 Now sometime it will be there and I want the script to pull that local module and if it's not there it should take the standard checkmarc.
现在有时它会在那里,我希望脚本提取该本地模块,如果不存在,则应使用标准的checkmarc。 I know I can do something like if the file in the path exists it'll take that, else do that, but I want to keep the import line just
import checkmarc
. 我知道我可以做一些类似的事情,如果路径中的文件存在,它将接受,否则,但是我想保持导入行只是
import checkmarc
。
From reading: https://docs.python.org/3/whatsnew/2.5.html#pep-328-absolute-and-relative-imports there's a section of exactly what I need but only for Python 2.4 and lower: 通过阅读: https : //docs.python.org/3/whatsnew/2.5.html#pep-328-absolute-and-relative-imports确实有一部分是我需要的,但仅适用于Python 2.4及更低版本:
In Python 2.4 and earlier, it will first look in the package's directory to perform a relative import, finds pkg/string.py, imports the contents of that file as the pkg.string module, and that module is bound to the name string in the pkg.main module's namespace.
在Python 2.4和更早版本中,它将首先在包的目录中执行相对导入,找到pkg / string.py,将该文件的内容作为pkg.string模块导入,然后将该模块绑定到名称字符串中。 pkg.main模块的名称空间。
If there's an elegant way to do it, I'd love to hear. 如果有一种优雅的方法,我很想听听。
I don't think you can do this if your custom module has the same name. 如果您的自定义模块名称相同,我认为您无法执行此操作。 You can however do something like this:
但是,您可以执行以下操作:
try:
import customcheckdmarc as checkdmarc
except ImportError:
import checkdmarc as checkdmarc
this will load your customecheckedmarc.py if it's there and will load default checkdmarc otherwise. 这将加载您的customecheckedmarc.py(如果存在),否则将加载默认的checkdmarc。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.