这里是我的文件夹结构:尝试相对进口超出顶层包
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
由于“多份原件打印”是在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
@MisterMiyagi:是的,你知道了 - 这里的这一行解析cli:https://github.com/wrye-bash/wrye-bash/blob/f739aba0aa09e4c1e12141bd9fcd268f760121c9/Mopy/bash/bash.py –
你应该把它移到'if __name__ ...',尽管它不能解决问题。我已经更新了答案,使得该软件包的优先级高于其模块。 – MisterMiyagi