javaproperties — Read & write Java .properties files in Python¶
Contents:
javaproperties
provides support for reading & writing Java .properties
files (both the “plain” format and XML) with a simple API based on the json
module — though, for recovering Java addicts, it also includes a Properties
class intended to match the behavior of Java 8’s java.net.Properties
as much as is
Pythonically possible.
Note
Throughout the following, “text string” means a Unicode character string —
unicode
in Python 2, str
in Python 3.
Reading & Writing .properties
Files¶
-
javaproperties.
dump
(props, fp, separator=u'=', comments=None, timestamp=True, sort_keys=False)[source]¶ Write a series of key-value pairs to a file in
.properties
format.Parameters: - props – A mapping or iterable of
(key, value)
pairs to write tofp
. All keys and values inprops
must be text strings. - fp – A file-like object to write the values of
props
to. It must have been opened as a text file with a Latin-1-compatible encoding. - separator (text string) – the string to use for separating keys & values. Only
" "
,"="
, and":"
(possibly with added whitespace) should ever be used as the separator. - comments (text string or
None
) – if non-None
,comments
will be written tofp
as a comment before any other content - timestamp (
None
,bool
, number, ordatetime.datetime
) – If neitherNone
norFalse
, a timestamp in the form ofMon Sep 12 14:00:54 EDT 2016
is written as a comment tofp
aftercomments
(if any) and before the key-value pairs. Iftimestamp
isTrue
, the current date & time is used. If it is a number, it is converted from seconds since the epoch to local time. If it is adatetime.datetime
object, its value is used directly, with naïve objects assumed to be in the local timezone. - sort_keys (bool) – if true, the elements of
props
are sorted lexicographically by key in the output
Returns: - props – A mapping or iterable of
-
javaproperties.
dumps
(props, separator=u'=', comments=None, timestamp=True, sort_keys=False)[source]¶ Convert a series of key-value pairs to a text string in
.properties
format.Parameters: - props – A mapping or iterable of
(key, value)
pairs to serialize. All keys and values inprops
must be text strings. - separator (text string) – the string to use for separating keys & values. Only
" "
,"="
, and":"
(possibly with added whitespace) should ever be used as the separator. - comments (text string or
None
) – if non-None
,comments
will be output as a comment before any other content - timestamp (
None
,bool
, number, ordatetime.datetime
) – If neitherNone
norFalse
, a timestamp in the form ofMon Sep 12 14:00:54 EDT 2016
is output as a comment aftercomments
(if any) and before the key-value pairs. Iftimestamp
isTrue
, the current date & time is used. If it is a number, it is converted from seconds since the epoch to local time. If it is adatetime.datetime
object, its value is used directly, with naïve objects assumed to be in the local timezone. - sort_keys (bool) – if true, the elements of
props
are sorted lexicographically by key in the output
Return type: text string
- props – A mapping or iterable of
-
javaproperties.
load
(fp, object_pairs_hook=<type 'dict'>)[source]¶ Parse the contents of the
readline
-supporting file-like objectfp
as a.properties
file and return adict
of the key-value pairs.fp
may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary filehandle, its contents are decoded as Latin-1.By default, the key-value pairs extracted from
fp
are combined into adict
with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hook
argument; it will be called with one argument, a generator of(key, value)
pairs representing the key-value entries infp
(including duplicates) in order of occurrence.load
will then return the value returned byobject_pairs_hook
.Parameters: - fp (file-like object) – the file from which to read the
.properties
document - object_pairs_hook (callable) – class or function for combining the key-value pairs
Return type: dict
of text strings or the return value ofobject_pairs_hook
- fp (file-like object) – the file from which to read the
-
javaproperties.
loads
(s, object_pairs_hook=<type 'dict'>)[source]¶ Parse the contents of the string
s
as a.properties
file and return adict
of the key-value pairs.s
may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1.By default, the key-value pairs extracted from
s
are combined into adict
with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hook
argument; it will be called with one argument, a generator of(key, value)
pairs representing the key-value entries ins
(including duplicates) in order of occurrence.loads
will then return the value returned byobject_pairs_hook
.Parameters: Return type: dict
of text strings or the return value ofobject_pairs_hook
Reading & Writing .properties
Files as XML¶
-
javaproperties.
dump_xml
(props, fp, comment=None, encoding=u'UTF-8', sort_keys=False)[source]¶ Write a series
props
of key-value pairs to a binary filehandlefp
in the format of an XML properties file. The file will include both an XML declaration and a doctype declaration.Parameters: - props – A mapping or iterable of
(key, value)
pairs to write tofp
. All keys and values inprops
must be text strings. - fp (binary file-like object) – a file-like object to write the values of
props
to - comment (text string or
None
) – if non-None
,comment
will be output as a<comment>
element before the<entry>
elements - encoding (string) – the name of the encoding to use for the XML document (also included in the XML declaration)
- sort_keys (bool) – if true, the elements of
props
are sorted lexicographically by key in the output
Returns: - props – A mapping or iterable of
-
javaproperties.
dumps_xml
(props, comment=None, sort_keys=False)[source]¶ Convert a series
props
of key-value pairs to a text string containing an XML properties document. The document will include a doctype declaration but not an XML declaration.Parameters: - props – A mapping or iterable of
(key, value)
pairs to serialize. All keys and values inprops
must be text strings. - comment (text string or
None
) – if non-None
,comment
will be output as a<comment>
element before the<entry>
elements - sort_keys (bool) – if true, the elements of
props
are sorted lexicographically by key in the output
Return type: text string
- props – A mapping or iterable of
-
javaproperties.
load_xml
(fp, object_pairs_hook=<type 'dict'>)[source]¶ Parse the contents of the file-like object
fp
as an XML properties file and return adict
of the key-value pairs.Beyond basic XML well-formedness,
load_xml
only checks that the root element is namedproperties
and that all of itsentry
children havekey
attributes; no further validation is performed.By default, the key-value pairs extracted from
fp
are combined into adict
with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hook
argument; it will be called with one argument, a generator of(key, value)
pairs representing the key-value entries infp
(including duplicates) in order of occurrence.load_xml
will then return the value returned byobject_pairs_hook
.Parameters: - fp (file-like object) – the file from which to read the XML properties document
- object_pairs_hook (callable) – class or function for combining the key-value pairs
Return type: dict
or the return value ofobject_pairs_hook
Raises: ValueError – if the root of the XML tree is not a
<properties>
tag or an<entry>
element is missing akey
attribute
-
javaproperties.
loads_xml
(s, object_pairs_hook=<type 'dict'>)[source]¶ Parse the contents of the string
s
as an XML properties document and return adict
of the key-value pairs.Beyond basic XML well-formedness,
loads_xml
only checks that the root element is namedproperties
and that all of itsentry
children havekey
attributes; no further validation is performed.By default, the key-value pairs extracted from
s
are combined into adict
with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hook
argument; it will be called with one argument, a generator of(key, value)
pairs representing the key-value entries ins
(including duplicates) in order of occurrence.loads_xml
will then return the value returned byobject_pairs_hook
.Parameters: Return type: dict
or the return value ofobject_pairs_hook
Raises: ValueError – if the root of the XML tree is not a
<properties>
tag or an<entry>
element is missing akey
attribute
Properties
Class¶
-
class
javaproperties.
Properties
(data=None, defaults=None)[source]¶ A port of Java 8’s
java.net.Properties
that tries to match its behavior as much as is Pythonically possible.Properties
behaves like a normalMutableMapping
class (i.e., you can doprops[key] = value
and so forth), except that it may only be used to store strings (str
andunicode
in Python 2; juststr
in Python 3). Attempts to use a non-string object as a key or value will produce aTypeError
.Parameters: - data (mapping or
None
) – A mapping or iterable of(key, value)
pairs with which to initialize theProperties
object. All keys and values indata
must be text strings. - defaults (
Properties
orNone
) – a set of default properties that will be used as fallback forgetProperty
-
defaults
= None¶ A
Properties
subobject used as fallback forgetProperty
. OnlygetProperty
,propertyNames
, andstringPropertyNames
use this attribute; all other methods (including the standard mapping methods) ignore it.
-
getProperty
(key, defaultValue=None)[source]¶ Fetch the value associated with the key
key
in theProperties
object. If the key is not present,defaults
is checked, and then itsdefaults
, etc., until either a value forkey
is found or the nextdefaults
isNone
, in which casedefaultValue
is returned.Parameters: - key (text string) – the key to look up the value of
- defaultValue – the value to return if
key
is not found in theProperties
object
Return type: text string (if
key
was found)Raises: TypeError – if
key
is not a string
-
load
(inStream)[source]¶ Update the
Properties
object with the entries in a.properties
file or file-like object.inStream
may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary filehandle, its contents are decoded as Latin-1.Parameters: inStream (file-like object) – the file from which to read the .properties
documentReturns: None
-
loadFromXML
(inStream)[source]¶ Update the
Properties
object with the entries in the XML properties fileinStream
.Beyond basic XML well-formedness,
loadFromXML
only checks that the root element is namedproperties
and that all of itsentry
children havekey
attributes; no further validation is performed.Parameters: inStream (file-like object) – the file from which to read the XML properties document Returns: None
Raises: ValueError – if the root of the XML tree is not a <properties>
tag or an<entry>
element is missing akey
attribute
-
propertyNames
()[source]¶ Returns a generator of all distinct keys in the
Properties
object and itsdefaults
(and itsdefaults
‘sdefaults
, etc.) in unspecified orderReturn type: generator of text strings
-
store
(out, comments=None)[source]¶ Write the
Properties
object’s entries (in unspecified order) in.properties
format toout
, including the current timestamp.Parameters: Returns:
-
storeToXML
(out, comment=None, encoding='UTF-8')[source]¶ Write the
Properties
object’s entries (in unspecified order) in XML properties format toout
.Parameters: - out (binary file-like object) – a file-like object to write the properties to
- comment (text string or
None
) – if non-None
,comment
will be output as a<comment>
element before the<entry>
elements - encoding (string) – the name of the encoding to use for the XML document (also included in the XML declaration)
Returns:
- data (mapping or
Low-Level Utilities¶
-
javaproperties.
escape
(field)[source]¶ Escape a string so that it can be safely used as either a key or value in a
.properties
file. All non-ASCII characters, all nonprintable or space characters, and the characters\ # ! = :
are all escaped using either\uXXXX
escapes (after converting non-BMP characters to surrogate pairs) or the single-character escapes recognized byunescape
.Parameters: field (text string) – the string to escape Return type: text string
-
javaproperties.
join_key_value
(key, value, separator=u'=')[source]¶ Join a key and value together into a single line suitable for adding to a
.properties
file.Parameters: - key (text string) – the key
- value (text string) – the value
- separator (text string) – the string to use for separating the key & value. Only
" "
,"="
, and":"
(possibly with added whitespace) should ever be used as the separator.
Return type: text string
-
javaproperties.
parse
(fp)[source]¶ Parse the contents of the
readline
-supporting file-like objectfp
as a.properties
file and return a generator of(key, value, original_lines)
triples, including duplicate keys and including comments & blank lines (which have theirkey
andvalue
fields set toNone
). This is the only way to extract comments from a.properties
file.fp
may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary filehandle, its contents are decoded as Latin-1.Parameters: fp (file-like object) – the file from which to read the .properties
documentReturn type: generator of triples of text strings
-
javaproperties.
to_comment
(comment)[source]¶ Convert a string to a
.properties
file comment. All non-Latin-1 characters in the string are escaped using\uXXXX
escapes (after converting non-BMP characters to surrogate pairs), a#
is prepended to the string, and a#
is inserted after any line breaks in the string not already followed by a#
or!
.Parameters: comment (text string) – the string to convert to a comment Return type: text string
-
javaproperties.
unescape
(field)[source]¶ Decode escape sequences in a
.properties
key or value. The following escape sequences are recognized:\t \n \f \r \uXXXX \\
If a backslash is followed by any other character, the backslash is dropped.
In addition, any valid UTF-16 surrogate pairs in the string after escape-decoding are further decoded into the non-BMP characters they represent. (Invalid & isolated surrogate code points are left as-is.)
Parameters: field (text string) – the string to decode Return type: text string
Command-Line Interface¶
javaproperties
includes two command-line programs for converting
.properties
files to & from the much more widely-supported JSON format.
Currently, only “plain”/non-XML properties files are supported.
json2properties¶
python -m javaproperties.fromjson [infile [outfile]]
# or, if the javaproperties package was properly installed:
json2properties [infile [outfile]]
Convert a JSON file infile
to a Latin-1 .properties
file and
write the results to outfile
. If not specified, infile
and
outfile
default to sys.stdin
and sys.stdout
, respectively.
The JSON document must be an object with scalar (i.e., string, numeric, boolean, and/or null) values; anything else will result in an error.
Output is sorted by key, and numeric, boolean, & null values are output using their JSON representations; e.g., the input:
{
"yes": true,
"no": "false",
"nothing": null
}
becomes:
#Mon Sep 26 18:57:44 UTC 2016
no=false
nothing=null
yes=true
properties2json¶
python -m javaproperties.tojson [infile [outfile]]
# or, if the javaproperties package was properly installed:
properties2json [infile [outfile]]
Convert a Latin-1 .properties
file infile
to a JSON object and
write the results to outfile
. If not specified, infile
and
outfile
default to sys.stdin
and sys.stdout
, respectively.