开发者

Python, import a modulo from a father directory

I want to know how import a file that is one level up. I read in google this:

>>> sys.path.append("../")

But I dont like it and i hope开发者_如何学C there are a better solution


Another option, if what you are writing is part of a package, is to use relative imports like so:

from .. import foo

where foo is the name of the module you're trying to import.

Similarly, if you've got another module in the current directory, you can use:

from . import bar

Sadly (or perhaps not so sadly), though, this doesn't extend any further than this. You can't go up to a grandparent, or higher.

EDIT:

As so graciously pointed out by JAB, my last comment there is not true:

from ...sys import path

Note that while that last case is legal, it is certainly discouraged ("insane" was the word Guido used).

I must have internalized Guido's description of it too much. ;^)

EDIT:

Okay, I just verified this in 2.7 - this apparently goes as deep as you like, and is dependent on the number of .

from .... import greatgrandparent

works juuuust fine. I think I'm going to need a bucket


Depending how your project is organized you may be able to import it normally. Lets say your project structure is like this:

/tmp/test_prj/launcher.py
/tmp/test_prj/mymodule/__init__.py
/tmp/test_prj/mymodule/helper.py
/tmp/test_prj/mymodule/mysubmodule/__init__.py

If you use a launcher (launcher.py in this case) and always calls your project with ./launcher.py you may import helper.py inside mysubmodule using the following line:

from mymodule import helper

This works because your current working directory is /tmp/test_prj. You can check it with print sys.path, it should be the first one.

Let me know if I wasn't clear enough :D

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜