我正在尝试从父目录导入文件,但到目前为止还没有运气:
.
├── e.py
├── __init__.py
├── q.py
└── subproject
├── __init__.py
├── sfile.py
这是代码sfile.py
import sys, os
topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir, os.pardir))
if os.path.exists(os.path.join(topdir, "project", "__init__.py")):
sys.path.insert(0, topdir)
from project import e
它给了我一个错误:
Traceback (most recent call last):
File "sfile.py", line 8, in <module>
from project import e
ImportError: No module named project
但是如果我去 python 解释器并做同样的事情,它会起作用:
>>> import os, sys
>>> topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir))
>>> if os.path.exists(os.path.join(topdir, "project", "__init__.py")):
... sys.path.insert(0, topdir)
...
>>> from project import e
IN e
>>>
这是我的e.py
文件:
print "IN e"
编辑:
sergey@sergey-PC:~/tmp/project/subproject$ ls
__init__.py __init__.pyc sfile.py sfile.pyc www.py www.pyc
sergey@sergey-PC:~/tmp/project/subproject$ pwd
/home/sergey/tmp/project/subproject
sergey@sergey-PC:~/tmp/project/subproject$ python
Python 2.7.3 (default, Apr 10 2013, 05:13:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.abspath(os.curdir)
'/home/sergey/tmp/project/subproject'
>>>
这是尝试做时的输出from .. import e
Traceback (most recent call last):
File "sfile.py", line 3, in <module>
from .. import e
ValueError: Attempted relative import in non-package
对于sys.argv[0]
: 在解释器中:
>>> import sys
>>> sys.argv[0]
''
>>>
print sys.argv[0]
在文件顶部添加时:
sergey@sergey-PC:~/tmp/project/subproject$ python sfile.py
sfile.py
更新sys.argv[0]
sergey@sergey-PC:~/tmp/project/subproject$ python sfile.py
/home/sergey/tmp/project/subproject/sfile.py
解释者:
>>> import os
>>> os.path.abspath(sys.argv[0])
'/home/sergey/tmp/project/subproject'
>>>