Sys module and serialization module (instance description) of the python module, and python serialization

Source: Internet
Author: User

Sys module and serialization module (instance description) of the python module, and python serialization

Sys module

The sys module is an interface for interacting with the python interpreter.

Sys. argv command line parameter List. The first element is the program path sys. exit (n) exit the program. exit (0) when the program Exits normally and exit sys by mistake. exit (1) sys. obtain the version information of the Python interpreter sys. path: return the search path of the module. during initialization, use the value of the PYTHONPATH environment variable sys. the name of the operating system platform returned by platform

Serialization Module

Serialization objective:

Make custom objects persistent in some storage form

Passing an object from one place to another

Make programs more maintainable

Json

# The Json module provides four functions: dumps, dump, loads, and loadimport jsondic = {'k1': 'v1 ', 'k2': 'v2', 'k3 ': 'v3 '} str_dic = json. dumps (dic) # serialization: converts a dictionary into a print (type (str_dic), str_dic) # <class 'str'> {"k3": "v3 ", "k1": "v1", "k2": "v2"} # note that the string in the dictionary after json conversion is "dic2 = json. loads (str_dic) # deserialization: converts a string-format dictionary into a dictionary # Note, the string in the dictionary of the string type to be processed using the json loads function must contain "" to indicate print (type (dic2), dic2) # <class 'dict '> {'k1 ': 'v1 ', 'k2': 'v2', 'k3': 'v3 '} list_dic = [1, ['A',' B ', 'C'], 3, {'k1 ': 'v1', 'k2': 'v2'}] str_dic = json. dumps (list_dic) # You can also process nested data types print (type (str_dic), str_dic) # <class 'str'> [1, ["a", "B ", "c"], 3, {"k1": "v1", "k2": "v2"}] list_dic2 = json. loads (str_dic) print (type (list_dic2), list_dic2) # <class 'LIST'> [1, ['A', 'B', 'C'], 3, {'k1 ': 'v1', 'k2': 'v2'}]
Import jsonf = open ('json _ file', 'w') dic = {'k1 ': 'v1', 'k2': 'v2', 'k3 ': 'v3 '} json. dump (dic, f) # The dump method receives a file handle and directly converts the dictionary into a json string and writes it to the file f. close () f = open ('json _ file') dic2 = json. load (f) # load method receives a file handle, directly converts the json string in the file into a data structure and returns f. close () print (type (dic2), dic2)
Import jsonf = open ('file', 'w') json. dump ({'nationality ': 'China'}, f) ret = json. dumps ({'nationality ': 'China'}) f. write (ret + '\ n') json. dump ({'nationality ': 'u.s.'}, f, ensure_ascii = False) ret = json. dumps ({'nationality ': 'u.s.'}, ensure_ascii = False) f. write (ret + '\ n') f. close () ensure_ascii keyword Parameter

Pickle

Json & pickle

Json, used for conversion between string and python Data Types

Pickle, used for conversion between python-specific types and python Data Types

# The pickle module provides four functions: dumps, dump (serialization, storage), loads (deserialization, read), and load (not only serialization dictionary, list... import pickledic = {'k1 ': 'v1', 'k2': 'v2', 'k3 ': 'v3 '} str_dic = pickle. dumps (dic) print (str_dic) # a string of binary content dic2 = pickle. loads (str_dic) print (dic2) # dictionary import timestruct_time = time. localtime (1000000000) print (struct_time) f = open ('pickle _ file', 'wb ') pickle. dump (struct_time, f) f. close () f = open ('pickle _ file', 'rb') struct_time2 = pickle. load (f) print (struct_time2.tm_year)

Shelve

# Shelve is also a serialization tool provided by python, which is easier to use than pickle. # Shelve only provides us with an open method, which is accessed with a key and used in a similar way as a dictionary. Import shelve = shelve. open ('shelve _ file') f ['key'] = {'int': 10, 'float': 9.5, 'string ': 'sample data'} # store data directly by operating on the file handle. close () import shelvef1 = shelve. open ('shelve _ file') existing = f1 ['key'] # You only need to use the key to retrieve data. However, if the key does not exist, an error f1.close () is returned () print (existing)
# This module has a limitation. It does not support multiple applications to write data to the same database at the same time. So when we know that our application only performs read operations, we can let shelve open DBimport shelve = shelve in read-only mode. open ('shelve _ file', flag = 'R') existing = f ['key'] f. close () print (existing)
# Because shelve does not record any modifications to the objects to be persisted by default, we need to modify the default parameters during shelve. open (). Otherwise, the changes to the objects will not be saved. Import shelvef1 = shelve. open ('shelve _ file') print (f1 ['key']) f1 ['key'] ['new _ value'] = 'this was not here before' f1. close () f2 = shelve. open ('shelve _ file', writeback = True) print (f2 ['key']) f2 ['key'] ['new _ value'] = 'this was not here before' f2. the close () "" writeback method has advantages and disadvantages. The advantage is that it reduces the probability of errors and makes object persistence more transparent to users. However, this method is not required in all cases. First, after using writeback, shelf will increase memory consumption during open (), and when DB closes (), it will write every object in the cache to the DB, this will also lead to additional waiting time. Because shelve has no way to know which objects are modified in the cache and which objects are not modified, all objects will be written. """

The sys module and serialization module (instance description) of the above python module are all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.