简体   繁体   中英

Adding Command Line Arguments to Python Twisted

I am still new to Python so keep that in mind when reading this.

I have been hacking away at an existing Python script that was originally "put" together by a few different people.

The script was originally designed to load it's 'configuration' using a module named "conf/config.py" which is basically Python code.

SETTING_NAME='setting value'

I've modified this to instead read it's settings from a configuration file using ConfigParser:

import ConfigParser
config_file_parser = ConfigParser.ConfigParser()
CONFIG_FILE_NAME = "/etc/service_settings.conf"
config_file_parser.readfp(open(r'' + CONFIG_FILE_NAME))
SETTING_NAME = config_file_parser.get('Basic', 'SETTING_NAME')

The problem I am having is how to specify the configuration file to use. Currently I have managed to get it working (somewhat) by having multiple TAC files and setting the "CONFIG_FILE_NAME" variable there using another module to hold the variable value. For example, I have a module 'conf/ConfigLoader.py":

global CONFIG_FILE_NAME

Then my TAC file has:

import conf.ConfigLoader as ConfigLoader
ConfigLoader.CONFIG_FILE_NAME = '/etc/service_settings.conf'

So the conf/config.py module now looks like:

import ConfigLoader
config_file_parser = ConfigParser.ConfigParser()
config_file_parser.readfp(open(r'' + ConfigLoader.CONFIG_FILE_NAME))

It works, but it requires managing two files instead of a single conf file. I attempted to use the "usage.Options" feature as described on http://twistedmatrix.com/documents/current/core/howto/options.html . So I have twisted/plugins/Options.py

from twisted.python import usage
global CONFIG_FILE_NAME

class Options(usage.Options):
    optParameters = [['conf', 'c', 'tidepool.conf', 'Configuration File']]

# Get config
config = Options()
config.parseOptions()
CONFIG_FILE_NAME = config.opts['conf']

That does not work at all. Any tips?

I don't know if I understood your problem.

If you want to load the configuration from multiple locations you could pass a list of filenames to the configparser: https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.read

If you were trying to make a generic configuration manager, you could create a class of a functions the receives the filename or you could use set the configuration file name in an environment variable and read that variable in your script using something like os.environ.get('CONFIG_FILE_NAME').

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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