2013-08-26 68 views
1

我一直在努力学习python-unipath,并且一直在掌握基本命令。然而,我一直被这个问题困扰。所以,我想获得当前文件的祖先(2)。所以,在Python解释器上,我做这样的事情:python unipath:当前文件目录(祖先)的路径不输出

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得到任何输出运行!没有导入错误。 我完全不知道为什么 - 可能真的很愚蠢。 希望得到任何帮助/方向这:(

回答

5

使用os.path.abspath(__file__)而不是__file__

这是因为__file__包含在你的情况相对路径。

__file__可以包含一个相对路径或绝对一个在不同的情况下:

所以,如果你不在sys.path中包含 模块的部分,你会得到一个绝对e路径。如果您位于包含该模块的sys.path的 部分中,则会得到相对路径。

如果您在当前目录中加载模块,并且当前的 目录不在sys.path中,您将获得绝对路径。

如果您在当前目录中加载模块,并且当前的 目录位于sys.path中,您将获得相对路径。

(引自Python __file__ attribute absolute or relative?

+0

非常感谢解决方案!现在接受你的答案:) – JohnJ

+0

只是一个后续问题:在所有情况下使用'os.path.abspath(__ file __)'作为默认值而不是'__file__'会更好吗? – JohnJ

+0

@JohnJ yup,将适用于所有情况。 – alecxe

3

如果您运行在该文件所在目录的脚本,__file__filename.py

>>> Path('a.py') 
Path(u'a.py') 
>>> Path('a.py').ancestor(2) 
Path(u'') 

通行证使用os.path.abspath绝对路径:

import os 

from unipath import Path 

ORM_ROOT = Path(os.path.abspath(__file__)).ancestor(2) 
print ORM_ROOT 

替代

您还可以使用absolute()方法。

Path('t.py').absolute().ancestor(2) 
+0

非常感谢你的回答 - 事实上你是对的。然而,要接受alecxe的回答基于时间:) – JohnJ

+0

@JohnJ,没关系。还有其他选择。 :) – falsetru

相关问题