我在打包一些模块时遇到棘手的ImportError,试图支持python 2.7和3.6。代码中没有任何内容可以排除其中一个版本,所以我想我会尝试。回购是https://github.com/raamana/neuropredict
之前只用2.7就行了。为了支持2.7和3.6, 经过大量的谷歌搜索和头脑缩减,我想我想出了如何使用我的包中每个模块顶部的以下导入代码来做到这一点:
from sys import version_info
if version_info.major==2 and version_info.minor==7:
import rhst, visualize
from freesurfer import aseg_stats_subcortical, aseg_stats_whole_brain
import config_neuropredict as cfg
elif version_info.major > 2:
from neuropredict import rhst, visualize
from neuropredict.freesurfer import aseg_stats_subcortical, aseg_stats_whole_brain
from neuropredict import config_neuropredict as cfg
else:
raise NotImplementedError('neuropredict supports only 2.7 or Python 3+. Upgrade to Python 3+ is recommended.')
目录结构是:
$ 22:19:54 miner neuropredict >> tree
.
├── config_neuropredict.py
├── freesurfer.py
├── __init__.py
├── __main__.py
├── model_comparison.py
├── neuropredict.py
├── rhst.py
├── test_rhst.py
└── visualize.py
init .py如下所示:
__all__ = ['neuropredict', 'rhst', 'visualize', 'freesurfer',
'config_neuropredict', 'model_comparison']
from sys import version_info
if version_info.major==2 and version_info.minor==7:
import neuropredict, config_neuropredict, rhst, visualize, freesurfer, model_comparison
elif version_info.major > 2:
from neuropredict import neuropredict, config_neuropredict, rhst, visualize, freesurfer, model_comparison
else:
raise NotImplementedError('neuropredict supports only 2.7 or Python 3+. Upgrade to Python 3+ is recommended.')
因此,当我在本地或CI上运行单元测试时,它可以通过上面的导入机制正常工作。
$ 22:19:25 miner neuropredict >> pytest test_rhst.py
=============================================================================================== test session starts ===============================================================================================
platform linux -- Python 3.6.1, pytest-3.2.1, py-1.4.34, pluggy-0.4.0
rootdir: /data1/strother_lab/praamana/neuropredict, inifile:
plugins: hypothesis-3.23.2
collected 1 item
test_rhst.py .
============================================================================================ 1 passed in 8.73 seconds =============================================================================================
$ 22:19:42 miner neuropredict >>
然而,当我直接运行neuropredict.py时,它会抛出错误
$ 22:19:57 miner neuropredict >> python ./neuropredict.py
Traceback (most recent call last):
File "neuropredict.py", line 23, in <module>
from neuropredict import rhst, visualize
File "/data1/strother_lab/praamana/neuropredict/neuropredict/neuropredict.py", line 23, in <module>
from neuropredict import rhst, visualize
ImportError: cannot import name 'rhst'
$ 22:29:39 miner neuropredict >> pwd
/data1/strother_lab/praamana/neuropredict/neuropredict
$ 22:29:43 miner neuropredict >>
这是在扼杀我 - 我需要弄清楚我犯了什么错误,或者我是在做一些亵渎神灵的事。
问题1:为什么我无法
python ./neuropredict.py
并获得一些解析器帮助,当测试脚本可以成功导入它?这曾经在许多其他场景中工作。让我发疯,因为我无法理解到底是怎么回事。
这是我需要实现的目标:
如果您需要更多详细信息或代码,我们将非常感谢您能快速访问此公共回购:https://github.com/raamana/neuropredict