简体   繁体   中英

python module importing error

I have the following structure:

AXBot:
    __init__.py
    bot.py
    util.py
    settings.py
    creator
        __init__.py
        xbot.py

The problem is that I cannot import the 'util' module in 'xbot.py' because python ends with 'ImportError: No module named util'... how can I solve?

PS: I am using the following code to import:

import util
import settings

Thank you.

Use relative importing

from . import util
from . import settings

I would recomment changing your folder hierarchy though, that looks cleaner to me. Also check your PYTHONPATH, it should normally work the way you did it.

References:

Try to stay away from sys.path hacks.

I think the namespacing is incorrect. From xbot.py, try using this import command

from AXBot import util
from AXBot import settings

It seems you're trying to run xbot.py from within the creator folder.

This is the output I get with xbot.py containing import util :

C:\Users\Luke\Python stuff\AXBot\creator>xbot.py
Traceback (most recent call last):
  File "C:\Users\Luke\Python stuff\AXBot\creator\xbot.py", line 4, in <module>
    import util
ImportError: No module named util

This is the output I get with xbot.py containing from . import util from . import util

C:\Users\Luke\Python stuff\AXBot\creator>xbot.py
Traceback (most recent call last):
  File "C:\Users\Luke\Python stuff\AXBot\creator\xbot.py", line 3, in <module>
    from . import util
ValueError: Attempted relative import in non-package

I also get this latter error with from .. import util instead of from . import util from . import util .

If you're running xbot.py from the directory containing it, Python can't tell that it's being run inside a package hierarchy. It thinks xbot.py isn't inside a package.

I replaced the line that attempted to import util with from AXBot import util , moved up a couple of directories and ran xbot.py using Python's -m command-line switch, which tells Python to run a module specified by module name instead of filename. Note that when you use -m , you pass in the fully-qualified name of the module, including the package hierarchy, but you don't include the file extension .py , because that's not part of the name of the module:

C:\Users\Luke\Python stuff\AXBot\creator>cd ..\..

C:\Users\Luke\Python stuff>python -m AXBot.creator.xbot
1232

I got the same output if I used import AXBot.util as util instead of from AXBot import util .

(I don't have your code to run, so instead I put a variable in util.py and attempted to print its value from within xbot.py . The value of this variable was 1232 .)

where you are is the most important question! according to that, you use the import . please update your question

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