简体   繁体   English

Python:从__file__目录导入配置文件?

[英]Python: Importing a config file from __file__ directory?

I have a script containing, among other things, the following structure. 我有一个脚本,其中包含以下结构。 Is the passage in "script_2.py" a good way to import variables from a external file regardless if the location of script_2.py and config.py is changed (assuming they will always "stay together")? 不管script_2.py和config.py的位置是否更改(假设它们将始终“保持在一起”),“ script_2.py”中的段落是否是从外部文件导入变量的好方法?

...Or am I missing something and making it more difficult than it should be? ...还是我错过了一些东西并使它变得比原本应该的困难?

# scrip_1.py
.
.
.
ThirdPartyBlackBoxProgramCall('somePath\\script_2.py')
.
.
.

.

# script_2.py
import os
import sys

folder_path = os.path.dirname(__file__)
sys.path.append(folder_path)
from config import A, B, C
.
.
.

.

# config.py
A = '111'
B = '222'
C = '333'

Think of it this way - if your package is installed by root into the system directory - there's no way for the user to override the defaults in your config file. 可以这样考虑-如果您的软件包是通过root用户安装到系统目录中的,则用户无法覆盖配置文件中的默认设置。

Instead of using a python file as the config, use an actual config module like ConfigParser and then do something like site.py does where it looks in the system directories, and then the user's home directory .yourpackage.rc 与其使用python文件作为配置,不如使用诸如ConfigParser之类的实际配置模块,然后执行类似于site.py的操作,该操作在系统目录中查找,然后在用户的主目录.yourpackage.rc中进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM