【发布时间】:2017-02-22 15:35:30
【问题描述】:
这是我的文件夹结构:
Mopy/ # no init.py !
bash/
__init__.py
bash.py # <--- Edit: yep there is such a module too
bass.py
bosh/
__init__.py # contains from .. import bass
bsa_files.py
...
test_bash\
__init__.py # code below
test_bosh\
__init__.py
test_bsa_files.py
在test_bash\__init__.py 我有:
import sys
from os.path import dirname, abspath, join, sep
mopy = dirname(dirname(abspath(__file__)))
assert mopy.split(sep)[-1].lower() == 'mopy'
sys.path.append(mopy)
print 'Mopy folder appended to path: ', mopy
在test_bsa_files.py:
import unittest
from unittest import TestCase
import bosh
class TestBSAHeader(TestCase):
def test_read_header(self):
bosh.bsa_files.Header.read_header()
if __name__ == '__main__':
unittest.main()
现在当我发布时:
python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\path\to\Mopy\test_bash\test_bosh\test_bsa_files.py true
我明白了:
Traceback (most recent call last):
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 124, in <module>
modules = [loadSource(a[0])]
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 43, in loadSource
module = imp.load_source(moduleName, fileName)
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py", line 4, in <module>
import bosh
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\bash\bosh\__init__.py", line 50, in <module>
from .. import bass
ValueError: Attempted relative import beyond toplevel package
既然“Mopy”在 sys.path 中并且 bosh\__init__.py 已正确解决,为什么它抱怨顶级包上方的相对导入?哪个是顶级包?
顺便说一句,这是我向遗留项目添加测试的尝试 - 在 Python test package layout 中提出过要求,但作为 Where do the Python unit tests go? 的副本被关闭。非常感谢对我当前测试包布局的评论!
answer below 在我的情况下不起作用:
模块 bash.py 是应用程序的入口点,其中包含:
if __name__ == '__main__':
main()
当我使用 import bash.bosh 或 from bash import bosh 时,我得到:
C:\_\Python27\python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Testing started at 3:45 PM ...
usage: utrunner.py [-h] [-o OBLIVIONPATH] [-p PERSONALPATH] [-u USERPATH]
[-l LOCALAPPDATAPATH] [-b] [-r] [-f FILENAME] [-q] [-i]
[-I] [-g GAMENAME] [-d] [-C] [-P] [--no-uac] [--uac]
[--bashmon] [-L LANGUAGE]
utrunner.py: error: unrecognized arguments: C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Process finished with exit code 2
此用法消息来自 bash 中的 main()。
【问题讨论】:
-
您在
bash.py中是否有任何未保护的代码与sys.argv或argparse一起使用?if __name__ == '__main__':不会在import bash或其任何变体上触发。 -
@MisterMiyagi:是的,你明白了 - 这里的这一行解析了 cli:github.com/wrye-bash/wrye-bash/blob/…
-
你应该把那个移到
if __name__ ...,虽然它不能解决问题。我已经更新了答案,赋予包比其模块更高的优先级。
标签: python python-2.7 python-import python-unittest relative-import