`importlib` 未使用/识别路径 [英] `importlib` not utilising/recognising path
问题描述
我试图在运行我的主要 python 脚本时使用较小的 setup.py
脚本导入模块.但是 importlib 命令:importlib.util.spec_from_file_location(name, location)
似乎没有检测到我的小 python 脚本.大概我没有正确填写 name
或 location
字段.
I am trying to import modules while running my main python script, using a smaller setup.py
script. However the importlib command: importlib.util.spec_from_file_location(name, location)
doesn't appear to be detecting my small python script. Presumably I'm not filling in the name
or location
fields correctly.
示例脚本 A (setup.py
):
import os
import pandas as pd
print("success!") # So I can see it has run.
示例脚本 B (my_script.py
):
import importlib
setup_path = ("/home/solebay/My Project Name/")
start_up_script = importlib.util.spec_from_file_location("setup.py", setup_path)
module = importlib.util.module_from_spec(start_up_script)
运行上面的代码片段返回:
Running the above snippet returns:
AttributeError: 'NoneType' object has no attribute 'loader'
我随后通过运行 type(start_up_script)
进行了调查,它给出的结果是 typeNone
.
I subsequently investigated by running type(start_up_script)
the result it gives is typeNone
.
路径正确.我通过运行以下命令验证了这一点:
The paths are correct. I verified this by running the following:
"/home/solebay/My Project Name/"
sudo python3 "/home/solebay/My Project Name/setup.py"
这些分别打印了消息is a directory
和success!
.
These printed the messages is a directory
and success!
respectively.
注意:Maurice Meyer 成功回答了我的主要问题,所以我已将其标记为正确.然而,我还没有达到我的主要目标;即通过另一个脚本导入模块.因此,如果这是您的目标,那么这个问题可能不适合您.
Note: Maurice Meyer succeeded in answering my main question, and so I have marked it as correct. However, I have not achieved my main goal; namely importing modules via another script. So if that is your aim, this question might not be appropriate for you.
推荐答案
传递给 spec_from_file_location
的 location
参数必须是 python 脚本的完整路径:>
The location
argument passed to spec_from_file_location
has to be the full path to the python script:
import importlib.util
spec = importlib.util.spec_from_file_location(
name='something__else', # name is not related to the file, it's the module name!
location='/tmp/solebay/My Project Name/setup.py' # full path to the script
)
my_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(my_mod)
print(my_mod)
出:
success!
<module 'something__else' from '/tmp/solebay/My Project Name/setup.py'>
这篇关于`importlib` 未使用/识别路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!