In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge about how Python configures the file yaml. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
YAML is an intuitive data serialization format that can be recognized by computers, easy to read by humans, and easy to interact with scripting languages. YAML is similar to XML, but the syntax is much simpler than XML and is simple and effective for converting to arrays or data that can be hash.
1. PyYaml
1. Load (): returns an object
Let's first create a yml file, config.yml:
Name: Tom Smithage: 37spouse: name: Jane Smithage: 25children:-name: Jimmy Smithage: 15-name1: Jenny Smith age1: 12
Read the yml file:
Import yamlf = open (ringing E:\ AutomaticTest\ Test_Framework\ config\ config.yml') y = yaml.load (f) print (y)
Results:
{'name':' Tom Smith', 'age': 37,' spouse': {'name':' Jane Smith', 'age': 25},' children': [{'name':' Jimmy Smith', 'age': 15}, {' name1': 'Jenny Smith',' age1': 12}]}
2. Load_all () generates an iterator
If the string or file contains several yaml documents, you can use yaml.load_all to parse all the documents.
Import yamlf ='- name: Jamesage: 20---name: Lilyage: 19 years after yaml.load_all (f) for data in y: print (data)
Execution result:
{'name':' James', 'age': 20}
{'name':' Lily', 'age': 19}
3. Yaml.dump generates a python object into an yaml document
Import yamlaproject = {'name':' Silenthand Olleander', 'race':' Human', 'traits': [' ONE_HAND', 'ONE_EYE']} print (yaml.dump (aproject,))
Execution result:
Name: Silenthand Olleander
Race: Human
Traits: [ONE_HAND, ONE_EYE]
The second parameter that yaml.dump receives must be an open text file or binary file, and yaml.dump will write the generated yaml document to the file.
Import yamlaproject = {'name':' Silenthand Olleander', 'race':' Human', 'traits': [' ONE_HAND', 'ONE_EYE']} f = open (rust:\ AutomaticTest\ Test_Framework\ config\ config.yml','w') print (yaml.dump (aproject,f))
4. Yaml.dump_all () outputs multiple segments to one file
Import yamlobj1 = {"name": "James", "age": 20} obj2 = ["Lily", 19] with open (rust:\ AutomaticTest\ Test_Framework\ config\ config.yml', 'w') as f: yaml.dump_all ([obj1, obj2], f)
Export to a file:
{age: 20, name: James}
-[Lily, 19]
II. Yaml grammar 1. Basic rules
1. Case sensitive
two。 Use indentation to represent hierarchical relationships
3. Tab is not allowed when indenting, only spaces are allowed
4. The number of indented spaces does not matter, as long as the elements at the same level are aligned to the left
5. # indicates a comment and is ignored from the beginning to the end of the line
2. Yaml to dictionary
The representation of a mapping or dictionary is supported in yaml, as follows:
# if you read the following format into Python, you will find a dictname: Gray blue age: 0job: Tester
Output:
{'name':' gray blue', 'age': 0,' job': 'Tester'}
3. Yaml transfer list
The representation of lists or arrays is supported in yaml, as follows:
# the following format reads list- gray blue-0-Tester in Python
Output:
['gray blue', 0, 'Tester']
4. Composite structure
Dictionaries and lists can be combined, as follows:
# read the following format: Python is a list containing dict- name: Gray blue age: 0 job: Tester- name: James age: 30
Output:
[{'name':' gray blue', 'age': 0,' job': 'Tester'}, {' name': 'James',' age': 30}]
5. Basic types
There are the following basic types in yaml:
String
Integer type
Floating point type
Boolean type
Null
time
Date
Let's write an example to see:
# this example outputs a dictionary where value includes all the basic types str: "Hello World!" int: 110float: 3.141boolean: true # or falseNone: null # you can also use the ~ sign to indicate nulltime: 2016-09-22t11:43:30.20+08:00 # ISO8601, written in Baidu date: 2016-09-22 # the same ISO8601
Output:
{'str':' Hello Worldworkers, 'int': 110,' float': 3.141, 'boolean': True,' None': None, 'time': datetime.datetime (2016, 9, 22, 3, 43, 30, 200000),' date': datetime.date (2016, 9, 22)}
If the string does not have spaces or special characters, you do not need to add quotation marks, but if there are spaces or special characters in it, you need to add quotation marks
Str: Gray blue str1: "Hello World" str2: "Hello\ nWorld"
Output:
{'str':' gray blue', 'str1':' Hello World', 'str2':' Hello\ nWorld'}
We should pay attention to the difference between single quotation marks and double quotation marks. Special characters in single quotation marks will be escaped when transferred to Python, that is, in the end, double quotation marks will not be escaped by Python, and special characters will be output at last; for example:
Str1: 'Hello\ nWorld'str2: "Hello\ nWorld"
Output:
{'str1':' Hello\\ nWorld', 'str2':' Hello\ nWorld'}
As you can see, the'\ n'in the single quotation mark is finally output, and the'\ n'in the double quote is finally escaped into a carriage return.
6. Citation
& and * for referencing
Name: & name gray blue tester: * name
This is equivalent to the following script:
Name: Gray Blue tester: Gray Blue
Output:
{'name':' gray blue', 'tester':' gray blue'}
7. Forced conversion
Yaml can be cast, use! Implementation, as follows:
Str:!! str 3.14int:!! int "123"
Output:
{'int': 123,' str': '3.14'}
It is obvious that 123 has been forcibly converted to int type, while float 3.14 has been forcibly converted to strtype.
8. Segment
In the same yaml file, you can use-to segment, so that multiple documents can be written in one file
-name: Jamesage: 20---name: Lilyage: 19 III. Constructors, representers, resolvers
1 、 yaml.YAMLObject
Yaml.YAMLObject registers a constructor (that is, the init () method in the code) with a metaclass, which allows you to turn the yaml node into a Python object instance, and use the demonstrator (that is, the repr () function in the code) to turn the Python object into a yaml node. Look at the code:
Import yamlclass Person (yaml.YAMLObject): yaml_tag ='! person' def _ init__ (self, name, age): self.name = name self.age = age def _ repr__ (self): return's (name=%s, age=%d)'% (self.__class__.__name__, self.name, self.age) james = Person ('James' 20) print (yaml.dump (james)) # Python object instance to yamllily = yaml.load ('! person {name: Lily, age: 19}') print (lily) # yaml to Python object instance
Output:
! person {age: 20, name: James}
Person (name=Lily, age=19)
2. Yaml.add_constructor and yaml.add_representer
You may not want to use the metaclass above, but you want to define a normal class, so you can use these two methods
Import yamlclass Person (object): def _ init__ (self, name, age): self.name = name self.age = age def _ repr__ (self): return 'Person (% s,% s)'% (self.name, self.age) james = Person ('James', 20) print (yaml.dump (james) # def person_repr (dumper) before adding a presenter Data): return dumper.represent_mapping (ubiquitous personalities, {"name": data.name, "age": data.age}) # mapping presenter For dictyaml.add_representer (Person, person_repr) # add a print (yaml.dump (james)) to an object using the add_representer method # after adding a demonstrator, def person_cons (loader, node): value = loader.construct_mapping (node) # mapping constructor For dict name = value ['name'] age = value [' age'] return Person (name, age) yaml.add_constructor (uplinghouse personalization, person_cons) # add a constructor lily = yaml.load ('! person {name: Lily, age: 19}') print (lily) to the specified yaml tag using the add_constructor method
Output:
!! python/object:__main__.Person {age: 20, name: James}
! person {age: 20, name: James}
Person (Lily, 19)
The first line is how ugly it was before the indicator was added! The middle line is changed into a standard format after adding a demonstrator, and a constructor is added below to convert the! person tag into a Person object.
IV. Examples
Yaml is a very clear and concise format, and it is very in tune with Python, and it is very easy to operate. When we build an automated testing framework, we can use yaml as a configuration file, or a use case file. Here is an example of a use case.
# Test using included Django testapp# First install python-django# Then launch the app in another terminal by doing# cd testapp# python manage.py testserver test_data.json# Once launched Tests can be executed via:# python resttest.py http://localhost:8000 miniapp-test.yaml---- config:-testset: "Tests using test app"-test: # create entity-name: "Basic get"-url: "/ api/person/"-test: # create entity-name: "Get single person"-url: "/ api/person/1/"-test: # create entity-name: "Get Single person "- url:" / api/person/1/ "- method: 'DELETE'- test: # create entity by PUT-name:" Create/update person "- url:" / api/person/1/ "- method:" PUT "- body:' {" first_name ":" Gaius " "id": 1, "last_name": "Baltar", "login": "gbaltar"}'- headers: {'Content-Type':' application/json'}-test: # create entity by POST-name: "Create person"-url: "/ api/person/"-method: "POST"-body:'{"first_name": "Willim", "last_name": "Adama" "login": "theadmiral"}'- headers: {Content-Type: application/json} these are all the contents of the article "how to configure yaml for Python" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.