本文整理汇总了Python中configparser.ConfigParser方法的典型用法代码示例。如果您正苦于以下问题:Python configparser.ConfigParser方法的具体用法?Python configparser.ConfigParser怎么用?Python configparser.ConfigParser使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类configparser
的用法示例。
在下文中一共展示了configparser.ConfigParser方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: write_config
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def write_config(self):
"""Write user's configuration file."""
logging.debug('[VT Plugin] Writing user config file: %s', self.vt_cfgfile)
try:
parser = configparser.ConfigParser()
config_file = open(self.vt_cfgfile, 'w')
parser.add_section('General')
parser.set('General', 'auto_upload', str(self.auto_upload))
parser.write(config_file)
config_file.close()
except:
logging.error('[VT Plugin] Error while creating the user config file.')
return False
return True
示例2: __init__
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def __init__(self, logfile=None, verbose=True):
"""
Wrapper for the SafeConfigParser class for easy use.
@attention: config_file argument may be file path or stream.
@param logfile: file handler or file path to a log file
@type logfile: file | FileIO | StringIO | None
@param verbose: No stdout or stderr messages. Warnings and errors will be only logged to a file, if one is given
@type verbose: bool
@return: None
@rtype: None
"""
super(ConfigParserWrapper, self).__init__(
label="ConfigParserWrapper", logfile=logfile, verbose=verbose)
self._config = ConfigParser()
self._config_file_path = None
示例3: copy_dependencies
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def copy_dependencies(f):
config_path = '/etc/yangcatalog/yangcatalog.conf'
config = ConfigParser.ConfigParser()
config._interpolation = ConfigParser.ExtendedInterpolation()
config.read(config_path)
yang_models = config.get('Directory-Section', 'save-file-dir')
tmp = config.get('Directory-Section', 'temp')
out = f.getvalue()
letters = string.ascii_letters
suffix = ''.join(random.choice(letters) for i in range(8))
dep_dir = '{}/yangvalidator-dependencies-{}'.format(tmp, suffix)
os.mkdir(dep_dir)
dependencies = out.split(':')[1].strip().split(' ')
for dep in dependencies:
for file in glob.glob(r'{}/{}*.yang'.format(yang_models, dep)):
shutil.copy(file, dep_dir)
return dep_dir
示例4: save_pyoptix_conf
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def save_pyoptix_conf(nvcc_path, compile_args, include_dirs, library_dirs, libraries):
try:
config = ConfigParser()
config.add_section('pyoptix')
config.set('pyoptix', 'nvcc_path', nvcc_path)
config.set('pyoptix', 'compile_args', os.pathsep.join(compile_args))
config.set('pyoptix', 'include_dirs', os.pathsep.join(include_dirs))
config.set('pyoptix', 'library_dirs', os.pathsep.join(library_dirs))
config.set('pyoptix', 'libraries', os.pathsep.join(libraries))
tmp = NamedTemporaryFile(mode='w+', delete=False)
config.write(tmp)
tmp.close()
config_path = os.path.join(os.path.dirname(sys.executable), 'pyoptix.conf')
check_call_sudo_if_fails(['cp', tmp.name, config_path])
check_call_sudo_if_fails(['cp', tmp.name, '/etc/pyoptix.conf'])
check_call_sudo_if_fails(['chmod', '644', config_path])
check_call_sudo_if_fails(['chmod', '644', '/etc/pyoptix.conf'])
except Exception as e:
print("PyOptiX configuration could not be saved. When you use pyoptix.Compiler, "
"nvcc path must be in PATH, OptiX library paths must be in LD_LIBRARY_PATH, and pyoptix.Compiler "
"attributes should be set manually.")
示例5: setUpClass
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def setUpClass(cls):
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
cls.db_kwargs = {'user': config['Database']['user'],
'password': config['Database']['password'],
'database': config['Database']['name'],
'host': config['Database']['host'],
'port': config['Database']['port']}
if 'create' in config['Database']:
cls.create = config['Database'].getboolean('create')
else:
cls.create = False
if cls.create:
Database.create(**cls.db_kwargs)
cls.db = Database(**cls.db_kwargs)
cls.db.clear()
示例6: setUp
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def setUp(self):
if not hasattr(sys.stdout, 'getvalue') and not hasattr(sys.stderr, 'getvalue'):
self.fail('This test needs to be run in buffered mode')
# Create temporal names for the registry
self.name = 'tmp' + uuid.uuid4().hex
self.name_reuse = 'tmp' + uuid.uuid4().hex
config = configparser.ConfigParser()
config.read(CONFIG_FILE)
# Create command
self.kwargs = {'user': config['Database']['user'],
'password': config['Database']['password'],
'host': config['Database']['host'],
'port': config['Database']['port']}
self.cmd = Init(database=self.name, **self.kwargs)
self.cmd_reuse = Init(database=self.name_reuse, **self.kwargs)
示例7: initialize_settings
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def initialize_settings():
import configparser
global_settings.cfg = configparser.ConfigParser()
global_settings.cfg.read(f"{dir_utils.get_main_dir()}/cfg/config.ini")
runtime_settings.tick_rate = float(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_TICK_RATE])
runtime_settings.cmd_hist_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_MULTI_LIM])
runtime_settings.cmd_token = global_settings.cfg[C_MAIN_SETTINGS][P_CMD_TOKEN]
runtime_settings.use_logging = global_settings.cfg.getboolean(C_LOGGING, P_LOG_ENABLE, fallback=False)
runtime_settings.max_logs = global_settings.cfg[C_LOGGING][P_LOG_MAX]
runtime_settings.cmd_queue_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_QUEUE_LIM])
runtime_settings.cmd_hist_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_HIST_LIM])
if len(runtime_settings.cmd_token) != 1:
rprint("ERROR: The command token must be a single character! Reverting to the default: '!' token.")
runtime_settings.cmd_token = '!'
# Initializes only safe-mode applicable plugins.
示例8: __init__
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def __init__(self):
self.web=webdriver.Chrome()
self.web.get('https://user.qzone.qq.com')
config = configparser.ConfigParser(allow_no_value=False)
config.read('userinfo.ini')
self.__username =config.get('qq_info','qq_number')
self.__password=config.get('qq_info','qq_password')
self.headers={
'host': 'h5.qzone.qq.com',
'accept-encoding':'gzip, deflate, br',
'accept-language':'zh-CN,zh;q=0.8',
'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
'connection': 'keep-alive'
}
self.req=requests.Session()
self.cookies={}
示例9: main
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def main(argv):
logging.basicConfig(level=logging.DEBUG)
config = configparser.ConfigParser()
config.read([
os.path.join(os.path.dirname(__file__), "config.default.ini"),
os.path.join(os.path.dirname(__file__), "config.ini"),
] + argv)
bind = config.get("server", "bind")
port = config.getint("server", "port")
app = make_app(config)
print("* Server name: ", config.get("server", "name"))
print("* Base url: ", config.get("server", "base_url"))
aiohttp.web.run_app(app, host=bind, port=port, access_log=None)
示例10: read_config
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def read_config():
_dict = {}
if getattr(sys, 'frozen', None):
config_path = os.path.join(os.path.dirname(sys.executable), 'config', 'config.ini')
else:
config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini')
if not os.path.exists(config_path):
print('can not find the config.ini, use the default sm uploader.'
'attention: this website may breakdown in the future, only used temporarily.')
_dict['picture_host'] = 'SmUploader'
return _dict
configs = ConfigParser()
configs.read(config_path)
_dict['picture_folder'] = configs['basic'].get('picture_folder', '')
_dict['picture_suffix'] = configs['basic'].get('picture_suffix', '')
_dict['picture_host'] = configs['basic'].get('picture_host', '')
_dict['config_path'] = config_path
if _dict['picture_host']:
_dict['uploader_info'] = configs[_dict['picture_host']]
return _dict
示例11: create
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def create(self, autostart=None):
if autostart is None:
autostart = self.autostart
execfile = '/usr/share/national-geographic-wallpaper/ngdownloader.py'
config = configparser.ConfigParser()
config['Desktop Entry'] = {
'Type': 'Application',
'Version': '1.0',
'Name': 'National Geographic Wallpaper',
'Exec': '/usr/bin/python3 {0}'.format(execfile),
'Hidden': 'false',
'NoDisplay': 'false',
'Terminal': 'false',
'StartupNotify': 'false',
'X-GNOME-Autostart-enabled': str(autostart).lower(),
'X-GNOME-Autostart-Delay': 5,
'X-GNOME-Autostart-Phase': 'Applications',
'X-MATE-Autostart-enabled': str(autostart).lower(),
'X-MATE-Autostart-Delay': 5,
'X-MATE-Autostart-Phase': 'Applications',
'NGV': '1.0'
}
with open(self.autostart_file, 'w') as configfile:
config.write(configfile)
示例12: _new_macro
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def _new_macro(self, opts):
if opts and opts['Name'] and opts['Command']:
btn = Factory.MacroButton()
btn.text = opts['Name']
btn.bind(on_press=partial(self.send, opts['Command']))
btn.ud = True
self.add_widget(btn)
# write it to macros.ini
try:
config = configparser.ConfigParser()
config.read(self.macro_file)
if not config.has_section("macro buttons"):
config.add_section("macro buttons")
config.set("macro buttons", opts['Name'], opts['Command'])
with open(self.macro_file, 'w') as configfile:
config.write(configfile)
Logger.info('MacrosWidget: added macro button {}'.format(opts['Name']))
except Exception as err:
Logger.error('MacrosWidget: ERROR - exception writing config file: {}'.format(err))
示例13: read_profiles
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def read_profiles(basepath, list_profiles):
"""
Parse Firefox profiles in provided location.
If list_profiles is true, will exit after listing available profiles.
"""
profileini = os.path.join(basepath, "profiles.ini")
LOG.debug("Reading profiles from %s", profileini)
if not os.path.isfile(profileini):
LOG.warning("profile.ini not found in %s", basepath)
raise Exit(Exit.MISSING_PROFILEINI)
# Read profiles from Firefox profile folder
profiles = ConfigParser()
profiles.read(profileini)
LOG.debug("Read profiles %s", profiles.sections())
if list_profiles:
LOG.debug("Listing available profiles...")
print_sections(get_sections(profiles), sys.stdout)
raise Exit(0)
return profiles
示例14: parse
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def parse():
parser = argparse.ArgumentParser(description='Train dialogue generator')
parser.add_argument('--mode', type=str, default='interact', help='train or test')
parser.add_argument('--model_path', type=str, default='sclstm.pt', help='saved model path')
parser.add_argument('--n_layer', type=int, default=1, help='# of layers in LSTM')
parser.add_argument('--percent', type=float, default=1, help='percentage of training data')
parser.add_argument('--beam_search', type=str2bool, default=False, help='beam_search')
parser.add_argument('--attn', type=str2bool, default=True, help='whether to use attention or not')
parser.add_argument('--beam_size', type=int, default=10, help='number of generated sentences')
parser.add_argument('--bs', type=int, default=256, help='batch size')
parser.add_argument('--lr', type=float, default=0.0025, help='learning rate')
parser.add_argument('--user', type=str2bool, default=False, help='use user data')
args = parser.parse_args()
config = configparser.ConfigParser()
if args.user:
config.read('config/config_usr.cfg')
else:
config.read('config/config.cfg')
config.set('DATA','dir', os.path.dirname(os.path.abspath(__file__)))
return args, config
示例15: parse
# 需要导入模块: import configparser [as 别名]
# 或者: from configparser import ConfigParser [as 别名]
def parse(is_user):
if is_user:
args = {
'model_path': 'sclstm_usr.pt',
'n_layer': 1,
'beam_size': 10
}
else:
args = {
'model_path': 'sclstm.pt',
'n_layer': 1,
'beam_size': 10
}
config = configparser.ConfigParser()
if is_user:
config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config/config_usr.cfg'))
else:
config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config/config.cfg'))
config.set('DATA', 'dir', os.path.dirname(os.path.abspath(__file__)))
return args, config