4

我有以下项目结构

SampleProject
     com
       python
          example
             source
                utils
                   ConfigManager.py
     conf
        constants.cfg

如何从 ConfigManager.py 访问 constants.cfg。

我有一个限制

  1. 我不能给出 constants.cfg 的完整路径(绝对路径),因为如果我在不同的 PC 上运行它应该无需任何修改即可工作
  2. 此外,如果我代表如下内容,我可以访问该文件。但我不想每次都回斜线

    filename = ..\\..\\..\\..\\..\\..\\constants.cfg`
    

目前我正在做这样的事情。但这仅在 constants.cfg 和 ConfigManager.py 位于同一目录中时才有效

currentDir =  os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
file = open(os.path.join(currentDir,'constants.cfg'))     
4

3 回答 3

4

如果conf是 Python 包,那么您可以使用pkgutil.get_data()

import pkgutil

data = pkgutil.get_data("conf", "constants.cfg")

或者如果setuptools安装了 - pkg_resources.resource_string()

import pkg_resources

data = pkg_resources.resource_string('conf', 'constants.cfg')

如果constants.cfg不在包中,则将其路径作为命令行参数传递,或将其设置在环境变量中,例如CONFIG_MANAGER_CONSTANTS_PATH,或从一组固定的默认路径中读取,例如os.path.expanduser("~/.config/ConfigManager/constants.cfg"). 要找到放置用户数据的位置,您可以使用appdirsmodule

如果您可以从不同的目录运行,则不能使用os.getcwd()它返回当前工作目录。ConfigManager.py出于同样的原因,相对路径"../../..."将不起作用。

如果您确定ConfigManager.pyconstants.cfg在文件系统中的相对位置不会改变:

import inspect
import os
import sys

def get_my_path():
    try:
        filename = __file__ # where we were when the module was loaded
    except NameError: # fallback
        filename = inspect.getsourcefile(get_my_path)
    return os.path.realpath(filename)

# path to ConfigManager.py
cm_path = get_my_path()
# go 6 directory levels up
sp_path = reduce(lambda x, f: f(x), [os.path.dirname]*6, cm_path)
constants_path = os.path.join(sp_path, "conf", "constants.cfg")
于 2013-06-22T04:06:50.327 回答
1

如果您在项目树的根目录中有一些模块,请说 config_loader.py,如下所示:

import os

def get_config_path():
    relative_path = 'conf/constants.cfg'
    current_dir = os.getcwd()
    return os.join(current_dir, relative_path)

然后在 ConfigManager.py 或任何其他需要配置的模块中:

import config_loader

file_path = config_loader.get_config_path()
config_file = open(file_path)

你甚至可以让你的 config_loader.py 只返回配置文件。

于 2013-06-21T21:37:28.960 回答
0

您可以在Python 3.0+中使用pathlib

这将获取跨不同平台的SampleProject文件夹中包含的任何文件的路径。

from pathlib import Path
def get_file(path):
    """
    returns the absolute path of a file
    :var
    str path
        the file path within the working dir
    :returns
    PureWindowsPath or PurePosixPath object
        type depends on the operating system in use
    """
    def get_project_root() -> Path:
    """Returns project root folder."""
    return Path(__file__).parent.parent

    return get_project_root().joinpath(path)

然后只需使用file_path作为参数调用该函数:

filePath = get_file('com/python/example/source/utils/configManager.py')

然后是通常的程序:

while open(filePath) as f:
    <DO YOUR THING>
于 2019-06-27T00:55:41.980 回答