[英]How do I import a python file through a path?
I am trying to make it so when this runs it runs the newest version in the list.我正在努力做到这一点,所以当它运行时它会运行列表中的最新版本。
Here is the directory I want:这是我想要的目录:
ClockOS:
bootLoader.py (the file I am starting at)
Versions:
Version 0.1.1:
main.py (Ignore because tis an older version)
Version 0.1.2:
main.py (The one I want to run/import)
I have tried loading through os.dir
, and using sys.path
, and adding an empty __init__.py
Anyone know how to get this working?我尝试通过
os.dir
加载,并使用sys.path
,并添加一个空的__init__.py
有人知道如何让它工作吗? My code:我的代码:
import os
import re
import sys
versionList = []
for filename in os.listdir('Versions'):
if filename.startswith('Version'):
versionList.append(filename)
print(f"Loaded {filename}")
def major_minor_micro(version):
major, minor, micro = re.search('(\d+)\.(\d+)\.(\d+)', version).groups()
return int(major), int(minor), int(micro)
latest = str(max(versionList, key=major_minor_micro))
print("Newest Version: ", latest)
os.path.dirname('Versions/'+str(latest))
sys.path.insert(1, latest)
print(sys.path)
import main
Lastly, I need this to work on both windows and linix, if that's possible.最后,如果可能的话,我需要这个在 windows 和 linix 上工作。
You need to use importlib
to do what you want.你需要使用
importlib
来做你想做的事。 Here is an example on how to import my_function
from a file:下面是如何从文件中导入
my_function
的示例:
spec = importlib.util.spec_from_file_location('some_module_name', filename)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
mod.my_function(1)
Probably the question is a duplicate of Import arbitrary python source file.可能问题是导入任意 python 源文件的副本。 (Python 3.3+)
(Python 3.3+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.