2

friends.a.py how to get b.py module

    fileA
    ├── fileB
    │    ├──a.py
    │    └── b.py
    └── fileC
          └── c.py

In a.py file, i can use this code to get function from b.py and run it:

module = __import__('b')
fun = getattr(module, 'run')
fun()

How can I get c.py function in a.py?

E.Tarrent
  • 89
  • 6

1 Answers1

0

End question. I have found some one had been ask this same question. link:How to import a module given the full path?

His answer: For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(Although this has been deprecated in Python 3.4.)

Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

See also. http://bugs.python.org/issue21436.

Community
  • 1
  • 1
E.Tarrent
  • 89
  • 6