首页 > 解决方案 > 如何指定在哪里查找文件和日志文件的路径?

问题描述

我有一个 python 脚本,它可能最终出现在不同服务器上的不同目录中。我的脚本有 sys.path.insert 行,它在其中查找库,并在与脚本相同的目录中查找 config.ini 文件。我希望能够使用完整路径运行脚本。

example.py

#!/usr/local/bin/python3.6
import sys, getopt, configparser
sys.path.insert(0, '../lib/')
from myFunctions import mySendmail, remoteFileChkSum, sendfile
...
def main():
    config = configparser.ConfigParser()
    # username and encrupted passwords are in config.ini
    # keys for encryption are in .keys
    config.read('config.ini')
    config.read('.keys')

在某些主机上/export/apps/bin/,该lib文件与/export/apps/lib. 在其他主机上,它/export/home/ray/bin与.lib/export/home/ray/lib

什么是最佳实践,以便我可以从任何主机上的任何位置运行脚本?我应该在开头找到脚本的目录/位置并执行os.chdir('<DIR>')吗?

标签: pythonworking-directory

解决方案


这就是我所做的并且有效。

import os, sys
script_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_dir)

sys.path.insert(0, '../lib/')
from myFunctions import mySendmail, remoteFileChkSum, sendfile


推荐阅读