2016-10-30 2 views
2

外部cfg(設定)ファイルからパスを読み取ることは可能ですか?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ファイルで使用してそのファイルを開くことができます。

答えて

1

使用self.config.get('direccion','enlace') i self.config.read('direccion', 'enlace')のnsteadとは、あなたは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+ 

がそれをこれをテストし、働く

+0

が機能しました。ありがとう! –

1

configパーサーサポートの読み取りディレクトリ。

いくつかの例:

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

更新Pythonコード:

CFG(私はあなたの設定ファイルから 'R +' を削除しました)

ファイルCFGファイル更新 https://wiki.python.org/moin/ConfigParserExamples

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')) 
関連する問題