简体   繁体   中英

Importing files in Python 3.4

I'm having trouble importing my own Python file. My file structure looks as such:

caboose2\
    __init__.py
    caboose.py
    bot\
        __init__.py
        settings.py
        config.ini

In the settings.py file there is a method, get_config() that uses configparser to parse the config.ini file to gather values for settings that are stored in a dict.

The contents of caboose.py are simple:

import bot
settings = bot.settings.get_config()

bot\\\\__init__.py contains:

import settings

And settings.py just contains the method get_config() . The method works fine; it was originally in the caboose.py file, but for cleanliness, I wanted to move it to its own file.

However, when I run the caboose.py file, I get this error:

Traceback (most recent call last):
File "caboose.py", line 2, in <module>
  import bot
File "D:\Brogramming\python\caboose2\bot\__init__.py", line 1, in <module>
  import settings
ImportError: No module named 'settings'

I'm sure there's some fundamental part of importing modules/files in Python that I'm not understanding, and I've decided to ask for help. Thank you for your time and any possible answers!

You are facing the issue because your first item sys.path still remains at caboose2\\ directory when the bot's __init__.py is run.

__init__.py is used for doing initialization logic for the module, you do not need to import settings.py into your __init__.py file.

Leave the __init__.py file empty and do the following in your caboose.py -

import bot.settings
settings = bot.settings.get_config()

If you really need to import settings.py in your __init__.py file, try -

from bot import settings

EDITED First read this - https://docs.python.org/3/tutorial/modules.html#packages

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

There are 2 options -

Eeither use the module export

If you wish to use the __init__.py then do this -

  • First add and __all__ to export the method from package -

File: __init__.py :

from settings import get_config
__all__ = ['get_config']

File: caboose.py :

from bot import get_config
settings = get_config()

OR Ignore the __init__.py completely and remove everything from inside it. Then the code in caboose.py will work automatically.

File: caboose.py :

import bot.settings
settings = bot.settings.get_config()

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