简体   繁体   中英

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 . (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:

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

put an __init__.py in each A/ B/ and C/. 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.

像这样使用import

from A.M import F as A_F

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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