Python memorandum

I had a chance to use Python, so I will write a memorandum. It may be difficult to read because I made a note of it. ..

How to use Config

Config uses ConfigParser.

config_path = "./setting.conf"
file = ConfigParser.SafeConfigParser()
file.read(config_path)
conf = init_context.InitContext(file)

The config is written like this

[host_settings]
host = 192.168.10.10
port = 8080

When using Specify like this

conf.get("host_settings", "host")

Run-time option specification

It is convenient to use OptParser for the optional parser

parser = OptionParser()
parser.usage = "usage: %prog [options] arg1 arg2"
parser.description = "Write a description"
parser.add_option("-f", action="store", type="string", dest="file",help="Explanation when reading the help")
parser.add_option("-d", action="store_true", dest="debug",help="debug mode", default=False)

If you write With option "-f" The argument specified by option -f When parsed, it can be used with the identifier file specified by dest.

When using the option "-d" If action = "store_true" is specified, True is entered in dest when the option is specified. default is the default value when no option is specified

The one specified by help is displayed when executed with "-h".

Use option analysis like this

(options, args) = parser.parse_args(sys.argv)
print options.file

File existence check

Check the existence before reading.

os.path.exists(file_path) 

Read CSV file

f = open(file_path, 'rb')
reader = csv.reader(f)
for Data in reader:
    print Data[0]
f.close

list memo

list.append

How to use the return value memo

You can also have two return values. user, name = method()

One liner

[method() for user in users if user.name == "yuta"]

If the name of the user element in users is yuta, you can call method. With this

for user in users :
	if user.name == "yuta":
		method()

How to use Request

url = "http://localhost:8080/target"
body = "json or xml"
	
response = requests.post(url, data=body)

I can throw a request

When using XML

import xml.etree.ElementTree as ET
element_tree  = ET.fromstring(xml_text)            #This is the route. This is converting a string to an XML element
code = element_tree.get("code")                    #After the conversion, you can get the value with the function of element. In this case the value of the code attribute
name = element_tree.find("name_list").get("name")  #In this case nama_The value of the name attribute of the list element
Body = ET.Element("root")
Body.set("name", "yuta")                               #Set the value of the name attribute of the root element"yuta"Add with
subbody = ET.SubElement(Body, "age")                   #Added age element to root element. Make that object a subbody.
subbody.text = 29                                      #The text of the subbody object is set as a value
ET.SubElement(Body, "address", {"city": "tokyo"})    #If you want to add more to the root object, do this. When adding more city attribute, value Saitama is added

If you want to add more under this guy, you'll need to save the object in a variable (for age) If you just add it to root, the element has already been added to Body above. For example

subbody = ET.SubElement(Body, "age") 
subbody.text = 29            

So if you want to add a child element

ET.SubElement(subBody, "birthday_party", {"old": 10, "with_who": "family"})
ET.SubElement(subBody, "birthday_party", {"old": 20, "with_who": "honey"})

You can do it like this.

Element tostring can be used to convert the created XML to a string If you use the following, encoding ='utf-8' will be added. Even if you do it with tostring, you cannot specify it as specified.

def to_xml_string(self, element):
    class dummy:
    pass

    data = []
    file = dummy()
    file.write = data.append
    ET.ElementTree(element).write(file, encoding="utf-8", xml_declaration=True)
    return "".join(data)

I want to summarize how to use Element separately.

Recommended Posts

Python Memorandum 2
Python memorandum
python memorandum
python memorandum
Python memorandum
python memorandum
Python memorandum
Python basics memorandum
Python pathlib memorandum
Python memorandum (algorithm)
Python memorandum [links]
Python memorandum numbering variables
python memorandum (sequential update)
Python
Python memorandum (personal bookmark)
Python basic memorandum part 2
[Python] Iterative processing_Personal memorandum
Memorandum @ Python OR Seminar
python memorandum super basic
Effective Python Learning Memorandum Day 15 [15/100]
Cisco Memorandum _ Python config input
Effective Python Learning Memorandum Day 6 [6/100]
Effective Python Learning Memorandum Day 12 [12/100]
Effective Python Learning Memorandum Day 9 [9/100]
Effective Python Learning Memorandum Day 8 [8/100]
ABC memorandum [ABC163 C --managementr] (Python)
About python beginner's memorandum function
Memorandum @ Python OR Seminar: matplotlib
[Python] SQLAlchemy error avoidance memorandum
A memorandum about correlation [Python]
Effective Python Learning Memorandum Day 14 [14/100]
Effective Python Learning Memorandum Day 1 [1/100]
Memorandum @ Python OR Seminar: Pulp
Effective Python Learning Memorandum Day 13 [13/100]
A memorandum about Python mock
Effective Python Learning Memorandum Day 3 [3/100]
Effective Python Learning Memorandum Day 5 [5/100]
Memorandum @ Python OR Seminar: Pandas
[python] Random number generation memorandum
Memorandum @ Python OR Seminar: scikit-learn
Effective Python Learning Memorandum Day 7 [7/100]
Effective Python Learning Memorandum Day 2 [2/100]
python parallel / asynchronous execution memorandum
Matplotlib memorandum
kafka python
linux memorandum
Python Summary
Built-in python
ABC memorandum [ABC159 C --Maximum Volume] (Python)
jinja2 memorandum
Python comprehension
Python technique
Python pywin32 (win32com) Excel operation memorandum
Studying python
Python 2.7 Countdown
Django memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics