简体   繁体   中英

Python importing everything from module subdirectory

I'm trying to import all files from a sub-directory, so I figured I could write __init__.py in that sub-directory to import the files. However, when I do this it does not seem to import anything.

File structure:

prog.py
module/
    __init__.py
    code.py

Code for prog.py : pass

Code for __init__.py : import code

Code for code.py : print('hello')

When I run prog.py nothing happens. Why does it not print hello , and is there a better way to easily import everything from a sub-directory?

If you have the following structure:

package
  __init__.py
  module.py

In __init__.py you can either try this:

import package.module

or this:

from . import module

This way, if package is in your PYTHONPATH , you'll get the expected behaviour:

>>> import package
hello

Put this in prog.py :

import module

Python will only load packages or modules that are imported.

To make it work, you probably need jcollado's answer as well.

Suppose you have a file structure like this:

prog.py
module/
    __init__.py
    code.py

Then import module would import the code in module/__init__.py and import module.code or from module import code would import the code in module/code.py under the local name "module.code" or "code".

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