這裏是我的文件夾結構:嘗試相對進口超出頂層包
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