구성 파일, 환경 및 명령 줄 인수를 구문 분석하여 단일 옵션 모음을 가져옵니다.
Python의 표준 라이브러리에는 구성 파일 구문 분석 ( configparser ), 환경 변수 읽기 ( os.environ ) 및 명령 줄 인수 구문 분석 ( argparse )을 위한 모듈이 있습니다 . 이 모든 작업을 수행하는 프로그램을 작성하고 싶습니다.
가지고 옵션 값의 폭포 :
- 기본 옵션 값, 재정의
- 구성 파일 옵션, 재정의
- 에 의해 재정의되는 환경 변수
- 명령 줄 옵션.
예 를 사용하여 명령 줄에 지정된 하나 이상의 구성 파일 위치를 허용
--config-file foo.conf하고이를 읽습니다 (일반 구성 파일 대신 또는 추가로). 이것은 여전히 위의 캐스케이드를 따라야합니다.수 있도록 한 곳에서 옵션 정의를 구성 파일 및 명령 줄의 구문 분석 동작을 결정합니다.
파싱 된 옵션을 옵션 값 의 단일 컬렉션으로 통합하여 프로그램의 출처를 신경 쓰지 않고 액세스 할 수 있습니다.
내가 필요한 모든 것은 분명히 파이썬 표준 라이브러리에 원활하게 작동하지 않습니다.
전형적인 표준 라이브러리에서 최소한의 수행 방법을 달성 할 수 있습니까?
argparse 모듈은 명령 줄처럼 보이는 구성 파일에 만족하는 한 제출 괴롭히지 재료. (사용자가 하나의 구문 만 배워야하기 때문에 장점이라고 생각합니다.) fromfile_prefix_chars 를 예를 들어으로 설정 @하면 다음과 같이됩니다.
my_prog --foo=bar
다음과 같다
my_prog @baz.conf
경우 @baz.conf이며,
--foo
bar
foo.conf수정 하여 코드가 자동으로 찾도록 할 수도 있습니다.argv
if os.path.exists('foo.conf'):
argv = ['@foo.conf'] + argv
args = argparser.parse_args(argv)
이러한 구성 파일의 형식은 ArgumentParser의 하위 클래스를 만들고 convert_arg_line_to_args 메서드를 추가 할 수 있습니다.
업데이트 : 나는 마침내 pypi에 넣었습니다. 다음을 통해 최신 버전을 설치하십시오.
pip install configargparser
원본 게시물
제가 함께 해킹 한 것이 있습니다. 의견에 개선 / 버그 보고서를 자유롭게 제안하십시오.
import argparse
import ConfigParser
import os
def _identity(x):
return x
_SENTINEL = object()
class AddConfigFile(argparse.Action):
def __call__(self,parser,namespace,values,option_string=None):
# I can never remember if `values` is a list all the time or if it
# can be a scalar string; this takes care of both.
if isinstance(values,basestring):
parser.config_files.append(values)
else:
parser.config_files.extend(values)
class ArgumentConfigEnvParser(argparse.ArgumentParser):
def __init__(self,*args,**kwargs):
"""
Added 2 new keyword arguments to the ArgumentParser constructor:
config --> List of filenames to parse for config goodness
default_section --> name of the default section in the config file
"""
self.config_files = kwargs.pop('config',[]) #Must be a list
self.default_section = kwargs.pop('default_section','MAIN')
self._action_defaults = {}
argparse.ArgumentParser.__init__(self,*args,**kwargs)
def add_argument(self,*args,**kwargs):
"""
Works like `ArgumentParser.add_argument`, except that we've added an action:
config: add a config file to the parser
This also adds the ability to specify which section of the config file to pull the
data from, via the `section` keyword. This relies on the (undocumented) fact that
`ArgumentParser.add_argument` actually returns the `Action` object that it creates.
We need this to reliably get `dest` (although we could probably write a simple
function to do this for us).
"""
if 'action' in kwargs and kwargs['action'] == 'config':
kwargs['action'] = AddConfigFile
kwargs['default'] = argparse.SUPPRESS
# argparse won't know what to do with the section, so
# we'll pop it out and add it back in later.
#
# We also have to prevent argparse from doing any type conversion,
# which is done explicitly in parse_known_args.
#
# This way, we can reliably check whether argparse has replaced the default.
#
section = kwargs.pop('section', self.default_section)
type = kwargs.pop('type', _identity)
default = kwargs.pop('default', _SENTINEL)
if default is not argparse.SUPPRESS:
kwargs.update(default=_SENTINEL)
else:
kwargs.update(default=argparse.SUPPRESS)
action = argparse.ArgumentParser.add_argument(self,*args,**kwargs)
kwargs.update(section=section, type=type, default=default)
self._action_defaults[action.dest] = (args,kwargs)
return action
def parse_known_args(self,args=None, namespace=None):
# `parse_args` calls `parse_known_args`, so we should be okay with this...
ns, argv = argparse.ArgumentParser.parse_known_args(self, args=args, namespace=namespace)
config_parser = ConfigParser.SafeConfigParser()
config_files = [os.path.expanduser(os.path.expandvars(x)) for x in self.config_files]
config_parser.read(config_files)
for dest,(args,init_dict) in self._action_defaults.items():
type_converter = init_dict['type']
default = init_dict['default']
obj = default
if getattr(ns,dest,_SENTINEL) is not _SENTINEL: # found on command line
obj = getattr(ns,dest)
else: # not found on commandline
try: # get from config file
obj = config_parser.get(init_dict['section'],dest)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): # Nope, not in config file
try: # get from environment
obj = os.environ[dest.upper()]
except KeyError:
pass
if obj is _SENTINEL:
setattr(ns,dest,None)
elif obj is argparse.SUPPRESS:
pass
else:
setattr(ns,dest,type_converter(obj))
return ns, argv
if __name__ == '__main__':
fake_config = """
[MAIN]
foo:bar
bar:1
"""
with open('_config.file','w') as fout:
fout.write(fake_config)
parser = ArgumentConfigEnvParser()
parser.add_argument('--config-file', action='config', help="location of config file")
parser.add_argument('--foo', type=str, action='store', default="grape", help="don't know what foo does ...")
parser.add_argument('--bar', type=int, default=7, action='store', help="This is an integer (I hope)")
parser.add_argument('--baz', type=float, action='store', help="This is an float(I hope)")
parser.add_argument('--qux', type=int, default='6', action='store', help="this is another int")
ns = parser.parse_args([])
parser_defaults = {'foo':"grape",'bar':7,'baz':None,'qux':6}
config_defaults = {'foo':'bar','bar':1}
env_defaults = {"baz":3.14159}
# This should be the defaults we gave the parser
print ns
assert ns.__dict__ == parser_defaults
# This should be the defaults we gave the parser + config defaults
d = parser_defaults.copy()
d.update(config_defaults)
ns = parser.parse_args(['--config-file','_config.file'])
print ns
assert ns.__dict__ == d
os.environ['BAZ'] = "3.14159"
# This should be the parser defaults + config defaults + env_defaults
d = parser_defaults.copy()
d.update(config_defaults)
d.update(env_defaults)
ns = parser.parse_args(['--config-file','_config.file'])
print ns
assert ns.__dict__ == d
# This should be the parser defaults + config defaults + env_defaults + commandline
commandline = {'foo':'3','qux':4}
d = parser_defaults.copy()
d.update(config_defaults)
d.update(env_defaults)
d.update(commandline)
ns = parser.parse_args(['--config-file','_config.file','--foo=3','--qux=4'])
print ns
assert ns.__dict__ == d
os.remove('_config.file')
할 것
이 구현은 아직 불완전합니다. 다음은 부분적인 TODO 목록입니다.
문서화 된 행동 준수
- (쉬운) 함수를 쓰기 것을 그림
dest에서args의add_argument대신에 의존의Action객체 - (사소한) 기록
parse_args된 함수를 사용parse_known_args. (예를 들어 , 호출을 보장하기parse_args위해cpython구현 에서 복사 합니다parse_known_args.)
덜 쉬운 것…
아직 시도한 적이 없습니다. 가능성은 낮지 만 여전히 가능합니다!
- (어려웠나요?) 상호 배제
- (하드?) 인수 그룹 (구현 된 경우 업그레이드 그룹은
section구성 파일에서 가져와야합니다.) - (하드?) 하위 명령 (하위 명령도
section구성 파일에 있어야 합니다.)
정확히 configglue 라는 라이브러리가 있습니다 .
configglue는 python의 optparse.OptionParser 및 ConfigParser.ConfigParser를 결합하는 라이브러리 선택 옵션을 구성 파일 및 명령 줄 인터페이스로 반복 할 때 할 필요가 있습니다.
또한 환경 변수를 지원 합니다.
라는 다른 라이브러리도 있습니다. ConfigArgParse 입니다
구성 파일 및 / 또는 환경 변수를 사용하여 옵션을 선택하십시오.
Łukasz Langa의 구성에 대한 PyCon 이야기에 관심이있을 수 있습니다.- 구성하자!
내가 직접 시도하려는 대부분 의 작업을 수행하는 ConfigArgParse 라이브러리가 있습니다.
구성 파일 및 / 또는 환경 변수를 사용하여 옵션을 선택하십시오.
자갈 각 프로그래머 떠나, 라이브러리는이 표준 문제를 해결하지 않는을 구석으로 같습니다 configparser과 argparse와 os.environ어설픈 방법으로 모두 함께.
내가 아는 한 표준 라이브러리는 제공하지 않습니다. 명령 줄 및 구성 파일 을 사용 optparse하고 ConfigParser구문 분석하고 그 위에 추상화 계층을 제공하는 코드를 작성하여 문제를 해결 합니다. 그러나 이전 의견에서 불쾌한 것처럼 보이는 별도의 요청이 있습니다.
작성한 코드를 내가보고 싶다면 http://liw.fi/cliapp/에 있습니다. 프레임 워크가 수행해야하는 작업의 대부분을 차지하기 때문에 "명령 줄 응용 프로그램 프레임 워크"라이브러리에 통합되었습니다.
[선택 사항 | arg] parse 및 configparser를 모두 사용하는 자체 라이브러리를 작성하는 것이 좋습니다.
처음 두 가지와 마지막 요구 사항이 주어지면 다음을 원합니다 말하고 싶습니다.
1 단계 : --config-file 옵션 만 찾는 명령 줄 구문 분석기 패스를 수행합니다.
2 단계 : 구성 파일을 구문 분석합니다.
3 단계 : 구성 파일 패스의 출력을 사용하여 두 번째 명령 줄 구문 분석기 패스를 설정합니다.
세 번째 요구 사항은 관심있는 optparse 및 configparser의 모든 기능을 노출 할 자체 옵션 정의 시스템을 설계하고 그 사이에 변환을 수행하기위한 배관을 작성해야 함을 의미합니다.
최근에 "optparse"를 사용하여 이와 같은 시도를했습니다.
나는 '--Store'및 '--Check'명령을 사용하여 OptonParser의 하위 클래스로 설정했습니다.
아래 코드는 거의 다룰 것입니다. 사전을 수락 / 반환하는 자체 '로드'및 '저장'방법을 정의하기 만하면됩니다.
class SmartParse(optparse.OptionParser):
def __init__(self,defaults,*args,**kwargs):
self.smartDefaults=defaults
optparse.OptionParser.__init__(self,*args,**kwargs)
fileGroup = optparse.OptionGroup(self,'handle stored defaults')
fileGroup.add_option(
'-S','--Store',
dest='Action',
action='store_const',const='Store',
help='store command line settings'
)
fileGroup.add_option(
'-C','--Check',
dest='Action',
action='store_const',const='Check',
help ='check stored settings'
)
self.add_option_group(fileGroup)
def parse_args(self,*args,**kwargs):
(options,arguments) = optparse.OptionParser.parse_args(self,*args,**kwargs)
action = options.__dict__.pop('Action')
if action == 'Check':
assert all(
value is None
for (key,value) in options.__dict__.iteritems()
)
print 'defaults:',self.smartDefaults
print 'config:',self.load()
sys.exit()
elif action == 'Store':
self.store(options.__dict__)
sys.exit()
else:
config=self.load()
commandline=dict(
[key,val]
for (key,val) in options.__dict__.iteritems()
if val is not None
)
result = {}
result.update(self.defaults)
result.update(config)
result.update(commandline)
return result,arguments
def load(self):
return {}
def store(self,optionDict):
print 'Storing:',optionDict
다음은 명령 줄 인수, 환경 설정, ini 파일 및 키링 값을 함께 읽는 해킹 한 모듈입니다. 요점 은 사용할 수 있습니다 .
"""
Configuration Parser
Configurable parser that will parse config files, environment variables,
keyring, and command-line arguments.
Example test.ini file:
[defaults]
gini=10
[app]
xini = 50
Example test.arg file:
--xfarg=30
Example test.py file:
import os
import sys
import config
def main(argv):
'''Test.'''
options = [
config.Option("xpos",
help="positional argument",
nargs='?',
default="all",
env="APP_XPOS"),
config.Option("--xarg",
help="optional argument",
default=1,
type=int,
env="APP_XARG"),
config.Option("--xenv",
help="environment argument",
default=1,
type=int,
env="APP_XENV"),
config.Option("--xfarg",
help="@file argument",
default=1,
type=int,
env="APP_XFARG"),
config.Option("--xini",
help="ini argument",
default=1,
type=int,
ini_section="app",
env="APP_XINI"),
config.Option("--gini",
help="global ini argument",
default=1,
type=int,
env="APP_GINI"),
config.Option("--karg",
help="secret keyring arg",
default=-1,
type=int),
]
ini_file_paths = [
'/etc/default/app.ini',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'test.ini')
]
# default usage
conf = config.Config(prog='app', options=options,
ini_paths=ini_file_paths)
conf.parse()
print conf
# advanced usage
cli_args = conf.parse_cli(argv=argv)
env = conf.parse_env()
secrets = conf.parse_keyring(namespace="app")
ini = conf.parse_ini(ini_file_paths)
sources = {}
if ini:
for key, value in ini.iteritems():
conf[key] = value
sources[key] = "ini-file"
if secrets:
for key, value in secrets.iteritems():
conf[key] = value
sources[key] = "keyring"
if env:
for key, value in env.iteritems():
conf[key] = value
sources[key] = "environment"
if cli_args:
for key, value in cli_args.iteritems():
conf[key] = value
sources[key] = "command-line"
print '\n'.join(['%s:\t%s' % (k, v) for k, v in sources.items()])
if __name__ == "__main__":
if config.keyring:
config.keyring.set_password("app", "karg", "13")
main(sys.argv)
Example results:
$APP_XENV=10 python test.py api --xarg=2 @test.arg
<Config xpos=api, gini=1, xenv=10, xini=50, karg=13, xarg=2, xfarg=30>
xpos: command-line
xenv: environment
xini: ini-file
karg: keyring
xarg: command-line
xfarg: command-line
"""
import argparse
import ConfigParser
import copy
import os
import sys
try:
import keyring
except ImportError:
keyring = None
class Option(object):
"""Holds a configuration option and the names and locations for it.
Instantiate options using the same arguments as you would for an
add_arguments call in argparse. However, you have two additional kwargs
available:
env: the name of the environment variable to use for this option
ini_section: the ini file section to look this value up from
"""
def __init__(self, *args, **kwargs):
self.args = args or []
self.kwargs = kwargs or {}
def add_argument(self, parser, **override_kwargs):
"""Add an option to a an argparse parser."""
kwargs = {}
if self.kwargs:
kwargs = copy.copy(self.kwargs)
try:
del kwargs['env']
except KeyError:
pass
try:
del kwargs['ini_section']
except KeyError:
pass
kwargs.update(override_kwargs)
parser.add_argument(*self.args, **kwargs)
@property
def type(self):
"""The type of the option.
Should be a callable to parse options.
"""
return self.kwargs.get("type", str)
@property
def name(self):
"""The name of the option as determined from the args."""
for arg in self.args:
if arg.startswith("--"):
return arg[2:].replace("-", "_")
elif arg.startswith("-"):
continue
else:
return arg.replace("-", "_")
@property
def default(self):
"""The default for the option."""
return self.kwargs.get("default")
class Config(object):
"""Parses configuration sources."""
def __init__(self, options=None, ini_paths=None, **parser_kwargs):
"""Initialize with list of options.
:param ini_paths: optional paths to ini files to look up values from
:param parser_kwargs: kwargs used to init argparse parsers.
"""
self._parser_kwargs = parser_kwargs or {}
self._ini_paths = ini_paths or []
self._options = copy.copy(options) or []
self._values = {option.name: option.default
for option in self._options}
self._parser = argparse.ArgumentParser(**parser_kwargs)
self.pass_thru_args = []
@property
def prog(self):
"""Program name."""
return self._parser.prog
def __getitem__(self, key):
return self._values[key]
def __setitem__(self, key, value):
self._values[key] = value
def __delitem__(self, key):
del self._values[key]
def __contains__(self, key):
return key in self._values
def __iter__(self):
return iter(self._values)
def __len__(self):
return len(self._values)
def get(self, key, *args):
"""
Return the value for key if it exists otherwise the default.
"""
return self._values.get(key, *args)
def __getattr__(self, attr):
if attr in self._values:
return self._values[attr]
else:
raise AttributeError("'config' object has no attribute '%s'"
% attr)
def build_parser(self, options, **override_kwargs):
"""."""
kwargs = copy.copy(self._parser_kwargs)
kwargs.update(override_kwargs)
if 'fromfile_prefix_chars' not in kwargs:
kwargs['fromfile_prefix_chars'] = '@'
parser = argparse.ArgumentParser(**kwargs)
if options:
for option in options:
option.add_argument(parser)
return parser
def parse_cli(self, argv=None):
"""Parse command-line arguments into values."""
if not argv:
argv = sys.argv
options = []
for option in self._options:
temp = Option(*option.args, **option.kwargs)
temp.kwargs['default'] = argparse.SUPPRESS
options.append(temp)
parser = self.build_parser(options=options)
parsed, extras = parser.parse_known_args(argv[1:])
if extras:
valid, pass_thru = self.parse_passthru_args(argv[1:])
parsed, extras = parser.parse_known_args(valid)
if extras:
raise AttributeError("Unrecognized arguments: %s" %
' ,'.join(extras))
self.pass_thru_args = pass_thru + extras
return vars(parsed)
def parse_env(self):
results = {}
for option in self._options:
env_var = option.kwargs.get('env')
if env_var and env_var in os.environ:
value = os.environ[env_var]
results[option.name] = option.type(value)
return results
def get_defaults(self):
"""Use argparse to determine and return dict of defaults."""
parser = self.build_parser(options=self._options)
parsed, _ = parser.parse_known_args([])
return vars(parsed)
def parse_ini(self, paths=None):
"""Parse config files and return configuration options.
Expects array of files that are in ini format.
:param paths: list of paths to files to parse (uses ConfigParse logic).
If not supplied, uses the ini_paths value supplied on
initialization.
"""
results = {}
config = ConfigParser.SafeConfigParser()
config.read(paths or self._ini_paths)
for option in self._options:
ini_section = option.kwargs.get('ini_section')
if ini_section:
try:
value = config.get(ini_section, option.name)
results[option.name] = option.type(value)
except ConfigParser.NoSectionError:
pass
return results
def parse_keyring(self, namespace=None):
"""."""
results = {}
if not keyring:
return results
if not namespace:
namespace = self.prog
for option in self._options:
secret = keyring.get_password(namespace, option.name)
if secret:
results[option.name] = option.type(secret)
return results
def parse(self, argv=None):
"""."""
defaults = self.get_defaults()
args = self.parse_cli(argv=argv)
env = self.parse_env()
secrets = self.parse_keyring()
ini = self.parse_ini()
results = defaults
results.update(ini)
results.update(secrets)
results.update(env)
results.update(args)
self._values = results
return self
@staticmethod
def parse_passthru_args(argv):
"""Handles arguments to be passed thru to a subprocess using '--'.
:returns: tuple of two lists; args and pass-thru-args
"""
if '--' in argv:
dashdash = argv.index("--")
if dashdash == 0:
return argv[1:], []
elif dashdash > 0:
return argv[0:dashdash], argv[dashdash + 1:]
return argv, []
def __repr__(self):
return "<Config %s>" % ', '.join([
'%s=%s' % (k, v) for k, v in self._values.iteritems()])
def comma_separated_strings(value):
"""Handles comma-separated arguments passed in command-line."""
return map(str, value.split(","))
def comma_separated_pairs(value):
"""Handles comma-separated key/values passed in command-line."""
pairs = value.split(",")
results = {}
for pair in pairs:
key, pair_value = pair.split('=')
results[key] = pair_value
return results
이를 위해 ChainMap을 사용할 수 있습니다. "파이썬의 명령 줄에서 구성 옵션을 재정 의 할 수있는 가장 좋은 방법은 무엇입니까 ?"에서 제가 할 제공 한 예제를 살펴보십시오. 그래서 질문.
내가 구축 한 도서관 시설 은 대부분의 요구 사항을 만족하는 것입니다.
- 주어진 파일 경로 또는 모듈 이름을 통해 구성 파일을 여러 번로드 할 수 있습니다.
- 주어진 접두사가있는 환경 변수에서 구성을로드합니다.
일부 클릭 명령 에 명령 줄 옵션을 첨부 할 수 있습니다.
(죄송합니다. argparse 아니지만는 클릭 이 더 좋고 훨씬 더 고급입니다.
confect향후 릴리스에서 argparse를 지원할 수 있습니다).- 가장 중요한
confect것은 JSON / YMAL / TOML / INI가 아닌 Python 구성 파일을로드 것입니다. IPython 프로필 파일 또는 DJANGO 설정 파일과 제출 Python 구성 파일은 유연하고 유지 관리가 제출합니다.
자세한 내용은 프로젝트 저장소 의 README.rst를 확인하십시오 . Python3.6 만 지원합니다.
예
명령 줄 옵션 연결
import click
from proj_X.core import conf
@click.command()
@conf.click_options
def cli():
click.echo(f'cache_expire = {conf.api.cache_expire}')
if __name__ == '__main__':
cli()
모든 속성과 코드가 자동으로 생성됩니다.
$ python -m proj_X.cli --help
Usage: cli.py [OPTIONS]
Options:
--api-cache_expire INTEGER [default: 86400]
--api-cache_prefix TEXT [default: proj_X_cache]
--api-url_base_path TEXT [default: api/v2/]
--db-db_name TEXT [default: proj_x]
--db-username TEXT [default: proj_x_admin]
--db-password TEXT [default: your_password]
--db-host TEXT [default: 127.0.0.1]
--help Show this message and exit.
환경 변수로드
환경 변수를로드 한 한 줄만 필요합니다.
conf.load_envvars('proj_X')
'IT' 카테고리의 다른 글
| ASP.NET 응용 프로그램을 라이브 서버에 어떻게 배포합니까? (0) | 2020.08.15 |
|---|---|
| 이중 슬래시로 시작하는 URL에 대한 브라우저 지원 (0) | 2020.08.15 |
| WPF의 MVVM-ViewModel에 모델의 변경 사항을 알리는 방법… (0) | 2020.08.15 |
| Visual Studio 2012를 Visual Studio 2010과 함께 사용합니까? (0) | 2020.08.15 |
| Timer & TimerTask 대 Thread + Sleep in Java (0) | 2020.08.15 |