python - 如何指定在哪里查找文件和日志文件的路径?
问题描述
我有一个 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>')
吗?
解决方案
这就是我所做的并且有效。
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
推荐阅读
- sql - 使用两个相关表中的最新关联数据显示表中的数据
- python - 返回类中的元组列表
- laravel - 调用数组上的成员函数 toBase()
- javascript - React:将函数作为道具传递给子组件,在子组件中调用onClick
- python-3.x - 我正在尝试“随机播放”一个音乐文件夹,并且 random.choice() 不断选择应该删除的内容时出现错误
- php - 从上传的文件创建图像
- java - 哪些类已注册/声明了哪些 URL?
- laravel - BitBucket - 错误:未能推送一些参考
- python - 如何在 Flask 上返回 400(错误请求)?
- mysql - 需要按日期查找重复记录