开发者

Relative import in python2.6.5

Relative import not working properly in python2.6.5 getting "ValueError: Attempted relative import in non-package".

I am 开发者_Python百科having all those __init__.py in proper place.


I have seen that error before when running a script that is actually inside a package. To the interpreter, it appears as though the package is not a package.

Try taking the script into another directory, putting your package inside your pythonpath, and import absolutely. Then, relative imports inside your package will work. NOTE: you can STILL not relatively import inside the end script - the easiest thing to do in this case is to make a "wrapper" script, that simply calls some entry point in your package.

You can go even further here by using setuptools to create a setup.py for your package, to make it distributable. Then, as a part of that, entry points would allow you to autogenerate scripts that called your package's code.

EDIT:

From your comment, it appears as though I wasn't quite clear. I'm not 100% sure of your directory structure because your comment above wasn't formatted, but I took it to be like this:

PythonEvent/
    main.py
    __init__.py
    DBConnector/
        __init__.py
        connector.py
    service/
        __init__.py
        myservice.py

When in myservice.py you have the line from ..DBConnector.connector import DBUpdate, the interpreter tries to import it relatively, UNLESS you are running myservice.py directly. This is what it appears you are doing.

Try making another dummy script outside of PythonEvent/ that is simply as follows:

from PythonEvent.service import myservice

if __name__ == '__main__':
    myservice.main() # or whatever the entry point is called in myservice.

Then, set your PYTHONPATH environment variable to point to the parent directory of PythonEvent/ (or move PythonEvent/ to your site-packages).


main.py
setup.py
Main Package/ ->
    __init__.py
    subpackage_a/ ->
       __init__.py
       module_a.py
    subpackage_b/ ->
       __init__.py
       module_b.py

i)

    1.You run python main.py
    2.main.py does: import app.package_a.module_a
    3.module_a.py does import app.package_b.module_b

ii)

    Alternatively 2 or 3 could use: from app.package_a import module_a

That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

Thanks to https://stackoverflow.com/a/1083169

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜