简体   繁体   中英

ImportError: How do I import a python module?

I've tried importing a Python module and failed. Here's my folder hierarchy:

package/
  folder/
    a.py
  utils/
    b.py

In module a.py I've tried importing b.py but received an ImportError .

How do I use function test from module b to a.py ?

Files:

a.py

def usetest():
    test()

b.py

def test():
    print("hello world")

Importing of Python modules can be done with a few different syntaxes:

  • A simple import... statement: import package.utils.b will now let you use package.utils.b.test() . Unfortunately it's quite long.
  • An import... as... statement: import package.utils.b as b will let you use b.test() .
  • A from... import... statement: from package.utils.b import test will let you use test() .
  • A from... import... as... statement: from package.utils.b import test as test_me will let you use test_me() .

All of these options will run the exact same function. Try putting them at the top of a.py .

Specifying the whole path, package.utils.b is called absolute form. You can also import in relative form:

  • import..utils.b as b will let you use b.test() . Notice the 2 dots at the start, saying go up one folder .
  • from..utils.b import test will let you use test() .
  • from..utils.b import test as test_me will let you use test_me() .

Each dot at the start specifies go up one folder, except one, which says "this folder".

If the main file you try to run is inside the package ( a.py ), you should switch to the directory that contains package, and run the file using -m . In your case, switch to the directory that contains package , and run python -m package.folder.a .

For more information about importing modules, see the Python Docs .

You can also dynamically import Python modules using their full path. It's more advanced and won't be covered in this answer.

package/ 
  folder/
    a.py
  utils/
    b.py

import:

if package is your main folder then use below syntax to import modules.

import utils.b as b
b.test() 
**or** 
from utils import b
**or**
To import only method
from utils.b import test
**or**
with alias name
from utils.b import test as my_test (my_test is the method alias name)

Import:

import folder.b as b b.test() or from folder.b import test or with alias name from folder.b import test as my_test (my_test is the alias name)

If the main file you try to run is inside the package (a.py), you should switch to the directory that contains package, and run the file using -m

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