是否可以从cfg文件中读取变量?

2024-10-01 07:40:46 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以从外部cfg(配置)文件读取路径。你知道吗

我正在制作一个打开文件的应用程序。目前我必须复制和粘贴路径多次。我想在我的cfg文件中编写路径并从Python程序中调用它。你知道吗

这是我的Python文件:

import ConfigParser
import os

class Messaging(object):

    def __init__(self):
        self.config = ConfigParser.RawConfigParser()
        self.rutaExterna = os.path.join(os.getcwd(), "app/properties.cfg")
        self.config.read(['properties.cfg', self.rutaExterna])

    def net(self):
        # with open('/etc/network/interfaces', 'r+') as f:
        direccion = self.config.read('direccion', 'enlace')
        with open('direccion') as f:
            for line in f:
                found_network = line.find('network')
                if found_network != -1:
                    network = line[found_network+len('network:'):]
                    print ('network: '), network
        return network

CFG文件:

[direccion]
enlace = '/etc/network/interfaces', 'r+'

我想将文件路径存储在cfg文件的变量中。你知道吗

然后我可以使用Python文件中的变量打开该文件。你知道吗


Tags: 文件importself路径configosdefline
2条回答

配置解析器支持读取目录。你知道吗

一些例子: https://wiki.python.org/moin/ConfigParserExamples

更新了CFG文件(我已经从配置文件中删除了r+)

CFG文件:

[direccion]
enlace = '/etc/network/interfaces'

更新的Python代码:

try:
    from configparser import ConfigParser  # python ver. < 3.0
except ImportError:
    from ConfigParser import ConfigParser  # ver. > 3.0

# instantiate
config = ConfigParser()
cfg_dir = config.get('direccion', 'enlace')

# Note: sometimes you might want to use os.path.join
cfg_dir = os.path.join(config.get('direccion', 'enlace'))

使用self.config.get('direccion','enlace')而不是self.config.read('direccion', 'enlace'),然后可以split()strip()字符串并将它们作为参数传递给open()

import ConfigParser
import os

class Messaging(object):

    def __init__(self):
        self.config = ConfigParser.RawConfigParser()
        self.rutaExterna = os.path.join(os.getcwd(), "app/properties.cfg")
        self.config.read(['properties.cfg', self.rutaExterna])

    def net(self):
        direccion = self.config.get('direccion','enlace')
        direccion = map(str.strip,direccion.split(','))
        with open(*direccion) as f:
            for line in f:
                found_network = line.find('network')
                if found_network != -1:
                    network = line[found_network+len('network:'):]
                    print ('network: '), network
        return network

msg = Messaging()
msg.net()

此外,配置文件中不需要'

[direccion]
enlace = /etc/network/interfaces, r+

测试了这个,它工作了。你知道吗

相关问题 更多 >