我一直在努力学习python-unipath并且已经掌握了基本命令。但是,我一直被这个问题难住了。所以,我想获取当前文件的祖先(2)。所以,在 python 解释器上,我做了这样的事情:
Python 2.7.3 (default, Jan 2 2013, 13:56:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from unipath import Path
>>> ORM_ROOT = Path("/home/foo/lump/foobar/turf/orm/unipath_try.py").ancestor(2)
>>> ORM_ROOT
Path('/home/foo/lump/foobar/turf')
..这是正确的,正是我想要的。 现在,我将其包装在一个文件中,如下所示:
# -*- coding: utf-8 -*-
# unipath_try.py
from unipath import Path
ORM_ROOT = Path(__file__).ancestor(2)
print ORM_ROOT
当我使用 python unipath_try.py 运行它时,我没有得到任何输出!也没有导入错误。 我完全不明白为什么会这样——可能真的很愚蠢。 将不胜感激对此的任何帮助/指导:(
请您参考如下方法:
使用 os.path.abspath(__file__) 而不是 __file__。
这是因为 __file__ 在您的案例中包含一个相对路径。
__file__ 在不同情况下可以包含相对路径或绝对路径:
So, if you aren't inside the part of sys.path that contains the module, you'll get an absolute path. If you are inside the part of sys.path that contains the module, you'll get a relative path.
If you load a module in the current directory, and the current directory isn't in sys.path, you'll get an absolute path.
If you load a module in the current directory, and the current directory is in sys.path, you'll get a relative path.
