我正在尝试从父目录导入文件,但到目前为止没有成功:
.
├── e.py
├── __init__.py
├── q.py
└── subproject
├── __init__.py
├── sfile.py
这是sfile.py
的代码
它给了我一个错误:
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'
>>>
你需要另一个奥斯帕迪尔为了实现这一点,因为第一个文件只是从文件跳转到同一个文件夹(在interperted中不会发生这种情况,因为您已经在该文件夹中):
当然,这是多余和烦人的。这个怎么样:
^{pr2}$更容易根据嵌套文件的级别进行更改(只需更改魔法数字3,甚至使其成为动态的)。在
相关问题 更多 >
编程相关推荐