简体   繁体   English

Mac python vs.spyder中的不同模块导入

[英]Different module import in Mac python vs. spyder

I have recently asked this question about importing an arbitrary amount of modules in python. 我最近问了这个问题,关于在python中导入任意数量的模块。 I received two good answers. 我收到了两个很好的答案。 Both worked when I programmed it in spyder. 当我在spyder中编程时,两者都起作用。

Today I ran the script from my terminal as test, since I'm planning to move my code to my server. 今天,我打算从终端运行脚本作为测试,因为我打算将代码移至服务器。 But this time the script crashed with this Traceback: 但是这次,脚本因以下回溯而崩溃:

File "evaluation.py", line 27, in __init__
self.solvers.append( __import__(file_name[:-3]) ) #cut away .py
ImportError: No module named 'v00'

The file architecture looks like this: 文件架构如下所示:

-evaluation.py
-evaluation
    -v00.py
    -v01.py

The code in evaluation.py which causes trouble is this one: Evaluation.py中引起麻烦的代码是以下代码:

os.chdir('evaluation')

for file_name in glob.glob("*.py"):
    self.solvers.append( __import__(file_name[:-3]) ) #cut away .py

for idx, solver in enumerate(self.solvers):
    self.dqn.append(solver.DQNSolver() )

Why does this work in spyder but not in the terminal? 为什么这在spyder中起作用但在终端中不起作用? They both use python 3.5 and I double checked that both are in the folder "evaluation" when executing the malicious line. 他们都使用python 3.5,在执行恶意代码时,我再次检查了它们是否都在“评估”文件夹中。

The typical way to handle this would be to turn the folder into a package by adding an empty __init__.py file and then import from the package with import evaluation.v00 (or the equivalent __import__ function call). 解决此问题的典型方法是通过添加一个空的__init__.py文件将文件夹变成一个包,然后使用import evaluation.v00 (或等效的__import__函数调用)从该包中import evaluation.v00 But you may run into problems as your main script has the same name as the package. 但是您可能会遇到问题,因为您的主脚本与软件包的名称相同。 I would suggest renaming one or the other 我建议重命名其中一个

-evaluationscript.py
-evaluation
    -__init__.py (empty file)
    -v00.py
    -v01.py

And then you probably need to use import_module instead of __import__ to populate solvers with the actual module (instead of the package). 然后你可能需要使用import_module而不是__import__填充solvers与实际模块(而不是封装)。

I'm not familiar with spyder, but if the same code is working there, then it may be adding the evaluation folder to the search path either with the PYTHONPATH env var, or by modifying sys.path . 我对spyder不熟悉,但是如果相同的代码在那里工作,则可能是通过PYTHONPATH env var或通过修改sys.path将评估文件夹添加到搜索路径中。

When you run a script, the path of the script is added to the default search path for module imports, but changing the folder using os.chdir won't affect that search path. 运行脚本时,脚本的路径将添加到模块导入的默认搜索路径,但是使用os.chdir更改文件夹不会影响该搜索路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM