TOML
official site: TOML: Tom's Obvious Minimal Language
official site for language packages: Home · toml-lang/toml Wiki · GitHub
older version tutorial (how to use [[...]]) Learn toml in Y Minutes
Intro.: https://en.wikipedia.org/wiki/TOML
TOML is a file format for configuration files. It is intended to be easy to read and write due to obvious semantics which aim to be "minimal", and is designed to map unambiguously to a dictionary.
TOML's syntax primarily consists of
key = "value"pairs,[section names], and# comments. TOML's syntax somewhat resembles that of .INI files, but it includes a formal specification, whereas the INI file format suffers from many competing variants.Its specification includes a list of supported data types: String, Integer, Float, Boolean, Datetime, Array, and Table.
example:
# This is a TOML document
title = "TOML Example"
[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00
[database]
enabled = true
ports = [ 8000, 8001, 8002 ]
data = [ ["delta", "phi"], [3.14] ]
temp_targets = { cpu = 79.5, case = 72.0 }
[servers]
[servers.alpha]
ip = "10.0.0.1"
role = "frontend"
[servers.beta]
ip = "10.0.0.2"
role = "backend"
Python and TOML
Check the Current Module
to check package name, version, and other details using pip see:
Check the version of Python package / library | note.nkmk.me
toml Module
official site and tutorial:
GitHub - uiri/toml: Python lib for TOML
Quick Tutorial
toml.loads takes in a string containing standard TOML-formatted data and returns a (nested) dictionary containing the parsed data.
>>> import toml >>> toml_string = """ ... # This is a TOML document. ... ... title = "TOML Example" ... ... [owner] ... name = "Tom Preston-Werner" ... dob = 1979-05-27T07:32:00-08:00 # First class dates ... ... [database] ... server = "192.168.1.1" ... ports = [ 8001, 8001, 8002 ] ... connection_max = 5000 ... enabled = true ... ... [servers] ... ... # Indentation (tabs and/or spaces) is allowed but not required ... [servers.alpha] ... ip = "10.0.0.1" ... dc = "eqdc10" ... ... [servers.beta] ... ip = "10.0.0.2" ... dc = "eqdc10" ... ... [clients] ... data = [ ["gamma", "delta"], [1, 2] ] ... ... # Line breaks are OK when inside arrays ... hosts = [ ... "alpha", ... "omega" ... ] ... """ >>> parsed_toml = toml.loads(toml_string)toml.dumps takes a dictionary and returns a string containing the corresponding TOML-formatted data.
>>> new_toml_string = toml.dumps(parsed_toml) >>> print(new_toml_string) title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002,] connection_max = 5000 enabled = true [clients] data = [ [ "gamma", "delta",], [ 1, 2,],] hosts = [ "alpha", "omega",] [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10"toml.dump (same convention as JSON, the commands regarding files are plural formed) takes a dictionary and a file descriptor and returns a string containing the corresponding TOML-formatted data.
>>> with open('new_toml_file.toml', 'w') as f: ... new_toml_string = toml.dump(parsed_toml, f) >>> print(new_toml_string) title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002,] connection_max = 5000 enabled = true [clients] data = [ [ "gamma", "delta",], [ 1, 2,],] hosts = [ "alpha", "omega",] [servers.alpha] ip = "10.0.0.1" dc = "eqdc10" [servers.beta] ip = "10.0.0.2" dc = "eqdc10"For more functions, view the API Reference below.
Note
For Numpy users, by default the data types
np.floatXwill not be translated to floats by toml, but will instead be encoded as strings. To get around this, specify theTomlNumpyEncoderwhen saving your data.>>> import toml >>> import numpy as np >>> a = np.arange(0, 10, dtype=np.double) >>> output = {'a': a} >>> toml.dumps(output) 'a = [ "0.0", "1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "7.0", "8.0", "9.0",]\n' >>> toml.dumps(output, encoder=toml.TomlNumpyEncoder()) 'a = [ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,]\n'API Reference
toml.load(f, _dict=dict)Parse a file or a list of files as TOML and return a dictionary.
Args:
f: A path to a file, list of filepaths (to be read into single object) or a file descriptor_dict: The class of the dictionary object to be returnedReturns: A dictionary (or object
_dict) containing parsed TOML dataRaises:
TypeError: Whenfis an invalid type or is a list containing invalid typesTomlDecodeError: When an error occurs while decoding the file(s)
toml.loads(s, _dict=dict)Parse a TOML-formatted string to a dictionary.
Args:
s: The TOML-formatted string to be parsed_dict: Specifies the class of the returned toml dictionaryReturns: A dictionary (or object
_dict) containing parsed TOML dataRaises:
TypeError: When a non-string object is passedTomlDecodeError: When an error occurs while decoding the TOML-formatted string
toml.dump(o, f, encoder=None)Write a dictionary to a file containing TOML-formatted data
Args:
o: An object to be converted into TOMLf: A File descriptor where the TOML-formatted output should be storedencoder: An instance ofTomlEncoder(or subclass) for encoding the object. IfNone, will default toTomlEncoderReturns: A string containing the TOML-formatted data corresponding to object
oRaises:
TypeError: When anything other than file descriptor is passed
toml.dumps(o, encoder=None)Create a TOML-formatted string from an input object
Args:
o: An object to be converted into TOMLencoder: An instance ofTomlEncoder(or subclass) for encoding the object. IfNone, will default toTomlEncoderReturns: A string containing the TOML-formatted data corresponding to object
o

本文介绍了TOML配置文件格式,展示了如何使用Python的toml模块进行数据解析和序列化,包括`toml.loads`和`toml.dumps`函数的实际操作示例。重点讲解了如何处理日期、数组和嵌套结构的数据。

1780

被折叠的 条评论
为什么被折叠?



