In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "how to set the default value in python configparser". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to set the default value in python configparser" can help you solve your doubts.
The setting of default value in configparser
When working on a project, in the read configuration file, when there is no corresponding project in the configuration file, if you want to set the default value, the previous practice is as follows:
Try: apple = config.get (section, 'apple') except NoSectionError, NoOptionError: apple = None
But when there are a lot of configurations, this is too bad.
Fortunately, there is a parameter of vars () in the Configparser.get () function, which can be customized. Note: only ConfigParser.ConfigParser;rawconfigparser is not supported.
Solution
1. Define the function:
Class DefaultOption (dict): def _ init__ (self, config, section, * * kv): self._config = config self._section = section dict.__init__ (self, * * kv) def items (self): _ items = [] for option in self: if not self._config.has_option (self._section, option): _ items.append ((option Self [option]) else: value_in_config = self._config.get (self._section, option) _ items.append ((option, value_in_config)) return _ items
2. Use
Def read_config (section, location): config = configparser.ConfigParser () config.read (location) apple= config.get (section, 'apple', vars=DefaultOption (config, section, apple=None)) pear= config.get (section,' pear', vars=DefaultOption (config, section, pear=None)) banana = config.get (section, 'banana', vars=DefaultOption (config, section) Banana=None) return apple, pear, banana
This is a good solution to automatically take the default value when there is no option when reading the configuration file, instead of using the rasie method to get the default value.
Stackoverflow from this solution
Considerations for using configparser
Take this very simple typical configuration file as an example:
[DEFAULT] ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = ys [bitbucket.org] User = HG [topsecret.server.com] Port = 50022ForwardX11 = no
1. Config parser operation is similar to dict, and the data access methods are basically the same.
> > import configparser > config = configparser.ConfigParser () > config.sections () [] > config.read ('example.ini') [' example.ini'] > config.sections () ['bitbucket.org' 'topsecret.server.com'] >' bitbucket.org' in configTrue > 'bytebong.com' in configFalse > config [' bitbucket.org'] ['User']' hg' > config ['DEFAULT'] [' Compression'] 'yes' > topsecret = config [' topsecret.server.com'] > topsecret ['ForwardX11']' no' > topsecret ['Port']' 50022'> > for key in config ['bitbucket.org']: print (key).. userroomsionlevelserveraliveintervalidationdx11 > > config [' bitbucket.org'] ['ForwardX11'] yes'
2. The default parameters of the default configuration item [DEFAULT] section will act on other Sections.
3. Data type
Config parsers will not guess or automatically analyze the data types that identify config.ini parameters, but will store them as strings. If you need to read them to other data types, you need to customize the conversion.
Special Boolean values: the getboolean () method is provided for the common Boolean values of 'yes'/'no',' on'/'off', 'true'/'false' and' 1 'impulse zero.
4. Get (), the method of obtaining parameter values.
Use the get () method to get the configuration value for each parameter item.
If the parameter in the general Sections is also set in [DEFAULT], then get () reaches the parameter value in [DEFAULT].
5. The parameter delimiter can be'='or':'(default)
6. You can use'#'or';'(default) to add comments or instructions
[Simple Values] key=valuespaces in keys=allowedspaces in values=allowed as wellspaces around the delimiter = obviouslyyou can also use: to delimit keys from values [All Values Are Strings] values like this: 1000000or this: 3.14159265359are they treated as numbers?: nointegers, floats and booleans are held as: stringscan use the API to get converted values directly: true [Multiline Values] chorus: I'm a lumberjack, and I'm okay I sleep all night and I work all day [No Values] key_without_valueempty string value here = [You can use comments] # like this Or this# By default only in an empty line.# Inline comments can be harmful because they prevent users# from using the delimiting characters as parts of values.# That being said, this can be customized. [Sections Can Be Indented] can_values_be_as_well = True does_that_mean_anything_special = False purpose = formatting for readability multiline_values = are handled just fine as long as they are indented deeper than the first line of a value # Did I mention we can indent comments, too?
7. Write configuration
Common practices:
Config.write (open ('example.ini', 'w'))
Reasonable practice:
With open ('example.ini', 'w') as configfile: config.write (configfile) points for attention
1. ConfigParser automatically filters out lines (contents) of'#'or'; 'comments during get.
In general, we manually annotate the configuration that is not needed temporarily with'#'. The problem is that the behavior of Configparser is the same as that of file object when wirte. If the configuration of annotation'#'is passed through get and then wirte to conf, then the configuration of'# 'will be lost.
Then you need a policy or rule. Does the configuration need to be manually edited? Or to build complex handling of native text, I suggest you stop it, avoid exposing important configurations to user editors, and keep in mind inline comments and Section comments.
A relatively simple method is:
For a single line of code, you can change the "#", ";" to other characters such as'@'or'^'(the commentator used in other languages such as bat is easy to understand), use the allow_no_value option, so that the comments will be saved as a configuration, and then change the "#", ";" back after processing.
2. After ConfigParser write, if the configuration text has the uppercase letter PRODUCT, it will become the lowercase letter product, which does not affect the correct read and write of the configuration.
After reading this, the article "how to set the default value in python configparser" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.