简体   繁体   English

通过路径导入python模块

[英]Importing a python module by path

I have the following mis-fortunate situation: 我有以下不幸的情况:

Three directories ( A , B and C ) contain a python module M with a function F . 三个目录( ABC )包含一个带函数F的python模块M (Those directories are not packages and it is impossible to change anything about the situation.) (这些目录不是软件包,因此无法更改任何情况。)

I am looking for a way to import them separately to access their functionalities. 我正在寻找一种单独导入它们以访问其功能的方法。 How do I need to import those modules to access F somewhat like this: 我需要如何导入这些模块来访问F ,如下所示:

A.F()
B.F()
C.F()

This will work, but it seems a bit inelegant... 这会起作用,但是看起来有点不雅...

import sys

sys.path.append("A")
import M as A

sys.path.pop()
del sys.modules['M']

sys.path.append("B")
import M as B

and so on...

You need to exec things into a new locals dictionary. 您需要将内容执行到新的本地字典中。 You can only get to the files you mention as files, not as modules, then stuff them into a moduletype. 您只能将您提到的文件作为文件而不是作为模块,然后将其填充为模块类型。

from types import ModuleType

with open("A/M.py") as a:
    A = ModuleType('A')
    exec a.read() in A.__dict__

with open("B/M.py") as b:
    B = ModuleType('B')
    exec b.read() in B.__dict__

with open("C/M.py") as c:
    C = ModuleType('C')
    exec c.read() in C.__dict__

Then access them like BF() as you wanted. 然后根据需要像BF()一样访问它们。 The only problem is the module metadata isn't set up correctly, so it will appear as a builtin. 唯一的问题是模块元数据设置不正确,因此将以内置形式显示。 You can even then do: 您甚至可以这样做:

import sys
sys.modules['A'] = A
sys.modules['B'] = B
sys.modules['C'] = C

and they will be importable like import A from other parts of your application. 它们可以像import A从应用程序的其他部分import A

put an __init__.py in each A/ B/ and C/. 在每个A / B /和C /中放置__init__.py The content of this file is 该文件的内容是

from M import F

Than the following code should work: 比以下代码更有效:

import A, B, C
A.F()
B.F()
C.F()

The __init__.py declares the directory as a package, and the statements in this file are executed when you import the package. __init__.py将目录声明为包,并且在导入包时执行此文件中的语句。

像这样使用import

from A.M import F as A_F

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

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