2016-02-09 68 views
1

假设文件结构(简体)看起来是这样的:Python的导入失败(在SLURM环境)

> some_script.py 
> +extra_directory/ 
> ++ __init__.py 
> ++ extra_script.py 

在我的Python文件some_script.py我有一些进口看起来像这样:

from extra_directory.extra_script import extra_class 

这在我的桌面上运行良好。

然而,当我在Slurm环境在集群上运行此,我总是得到这个错误:

Traceback (most recent call last): File "/work/var/slurmd/state.node253.d/job17281/slurm_script", line 2, in from distributions.convert_to_distribution import DistributionConverter as DC ImportError: No module named distributions.convert_to_distribution

凡分布的东西是extra_directory例子的真实姓名。

任何想法?

编辑:

为了澄清我的情况:我其实在每个目录__init__.py脚本(只是忘了在这里提到它)。然而,进口仍然失败

我现在的解决方法是添加在我的脚本的绝对路径:

sys.path.append("/absolute/path/to/extra_directory") 
+0

你确定你的脚本在目录开始,你认为它已经开始?脚本标题是什么样的? – damienfrancois

回答

0

您需要创建一个空文件__init__.pyextra_directory这样Python将把extra_directory作为一个Python包。

根据Modules - Python Documentation

The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later.

文件结构应该是这样的:

> some_script.py 
> extra_directory/ 
>  __init__.py 
>  extra_script.py 

应该有一个名为extra_classextra_script.py类。

class extra_script(object): 
    pass 

然后你可以从some_script.py成功导入:

from extra_directory.extra_script import extra_class 
+0

谢谢你的回答!我想有人总是忘记'__init __。py'。但是,我在每个目录都有init,但是导入失败。目前我的解决方法是包含绝对路径,以我的额外目录:'sys.path.append(“/绝对/路径/到/ extra_directory”)' – daniel451