我正在尝试在目录 /home/kurt/dev/clones/ipercron-utils/tester 中导入一个 Python 模块。此目录包含一个 tester.py 和一个 config.yml 文件。 tester.py 包含(前导)行
config = yaml.safe_load(open("config.yml"))
现在,我尝试从另一个目录导入它:
import sys
sys.path.insert(0, "/home/kurt/dev/clones/ipercron-utils/tester")
import tester
但是,我收到以下错误:
Traceback (most recent call last):
File "/home/kurt/dev/clones/ipercron-compose/controller/controller_debug2.py", line 9, in <module>
import tester
File "/home/kurt/dev/clones/ipercron-utils/tester/tester.py", line 28, in <module>
config = yaml.safe_load(open("config.yml"))
IOError: [Errno 2] No such file or directory: 'config.yml'
据我了解,Python 正在当前目录 (/home/kurt/dev/clones/ipercron-compose/controller 中寻找 config.yml 文件) 而我希望它在导入模块的目录中查找 (/home/kurt/dev/clones/ipercron-utils/tester)。有什么办法可以指定吗?
请您参考如下方法:
__file__ 始终包含当前模块文件路径(此处为 /home/kurt/dev/clones/ipercron-utils/tester/tester.py)。
只需对其执行 dirname => 你就有了包含你的 yml 配置文件的路径。
在您的 tester.py 模块中像这样编码(import os 如果尚未完成):
module_dir = os.path.dirname(__file__)
config = yaml.safe_load(open(os.path.join(module_dir,"config.yml")))
旁注:当代码使用 py2exe“编译”时,__file__ 对主文件不起作用。在这种情况下,你必须这样做:
module_dir = os.path.dirname(sys.executable)
