Giter VIP home page Giter VIP logo

javaproperties's Introduction

Project Status: Active - The project has reached a stable, usable
state and is being actively developed. CI Status coverage pyversions MIT License

GitHub | PyPI | Documentation | Issues | Changelog

javaproperties provides support for reading & writing Java .properties files_ (both the simple line-oriented 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.util.Properties_ as much as is Pythonically possible.

Previous versions of javaproperties included command-line programs for basic manipulation of .properties files. As of version 0.4.0, these programs have been split off into a separate package, javaproperties-cli_.

Installation

javaproperties requires Python 3.8 or higher. Just use pip for Python 3 (You have pip, right?) to install it:

python3 -m pip install javaproperties

Examples

Dump some keys & values (output order not guaranteed):

>>> properties = {"key": "value", "host:port": "127.0.0.1:80", "snowman": "β˜ƒ", "goat": "🐐"} >>> print(javaproperties.dumps(properties)) #Mon Sep 26 14:57:44 EDT 2016 key=value goat=ud83dudc10 host:port=127.0.0.1:80 snowman=u2603

Load some keys & values:

>>> javaproperties.loads(''' ... #Mon Sep 26 14:57:44 EDT 2016 ... key = value ... goat: \ud83d\udc10 ... host\:port=127.0.0.1:80 ... #foo = bar ... snowman β˜ƒ ... ''') {'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': 'β˜ƒ'}

Dump some properties to a file and read them back in again:

>>> with open('example.properties', 'w', encoding='latin-1') as fp: ... javaproperties.dump(properties, fp) ... >>> with open('example.properties', 'r', encoding='latin-1') as fp: ... javaproperties.load(fp) ... {'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': 'β˜ƒ'}

Sort the properties you're dumping:

>>> print(javaproperties.dumps(properties, sort_keys=True)) #Mon Sep 26 14:57:44 EDT 2016 goat=ud83dudc10 host:port=127.0.0.1:80 key=value snowman=u2603

Turn off the timestamp:

>>> print(javaproperties.dumps(properties, timestamp=None)) key=value goat=ud83dudc10 host:port=127.0.0.1:80 snowman=u2603

Use your own timestamp (automatically converted to local time):

>>> print(javaproperties.dumps(properties, timestamp=1234567890)) #Fri Feb 13 18:31:30 EST 2009 key=value goat=ud83dudc10 host:port=127.0.0.1:80 snowman=u2603

Dump as XML:

>>> print(javaproperties.dumps_xml(properties)) <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="key">value</entry> <entry key="goat">🐐</entry> <entry key="host:port">127.0.0.1:80</entry> <entry key="snowman">β˜ƒ</entry> </properties>

New in v0.6.0: Dump Unicode characters as-is instead of escaping them:

>>> print(javaproperties.dumps(properties, ensure_ascii=False)) #Tue Feb 25 19:13:27 EST 2020 key=value goat=🐐 host:port=127.0.0.1:80 snowman=β˜ƒ

And more!

javaproperties's People

Contributors

dependabot[bot] avatar jwodder avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

javaproperties's Issues

Support for properties dict while retaining comments?

Hey there,

I've been looking for a full-featured library to handle Java properties and your implementation looks to be the most thorough on the internet, so +1 for that. :) My use case is that I want to be able to load a .properties file, change just a handful of lines, and then serialize it back to a file (while retaining comments, blank lines, etc.). I've discovered the low-level parse method which returns a generator of tuples, but is there an in-built way to create an object from a .properties file which has k-v lookup/modification along with the ability to serialize back to a file with comments?

If not, would you be open to a PR to add such support? I'd be happy to do it if you could give me guidance on how you'd prefer the design to look.

Building fails with Python 3.x in a non-unicode environment

OS: FreeBSD 11.2-RELEASE-p9 amd64/i386 (applies also for 12.0-RELEASE-p3)
Python version: 3.6.8
javaproperties version: 0.5.1

The Python package is created in a pristine environment that has only the Python runtime and the Package "setuptools" as a basic dependency set.

Building the package fails with Python 3.x in a non-unicode environment (= LANG variable is not set) with:

# python3.6 setup.py build
Traceback (most recent call last):
File "setup.py", line 6, in <module>
for line in fp:
File "/usr/local/lib/python3.6/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 244: ordinal not in range(128)

A quick workaround for this issue is to add "fp.seek(256)" after the "with open [...]" statement to get past the unicode characters in ./javaproperties/init.py

dump_xml () method, TypeError: write() argument must be str, not bytes

Hello,

I would like to report an abnormal case on dump_xml method with below code and output.
Please let me know if I am misusing in system default, UTF8 locale environment.

test code

import javaproperties
import traceback

properties = {"key": "value", "host:port": "127.0.0.1:80", "snowman": "β˜ƒ", "goat": "🐐"}

with open('text.properties', 'w') as wf:
    javaproperties.dump(properties, wf, sort_keys=True)

try:
    with open('xml.properties', 'w') as wf:
        javaproperties.dump_xml(properties, wf, sort_keys=True)
except Exception as exc:
    traceback.print_exc()

with open('xml.properties', 'w') as wf:
    print(javaproperties.dumps_xml(properties, sort_keys=True), file=wf)    
    
with open('text.properties', 'r') as rf:
    print('text.properties:')
    print(javaproperties.load(rf))

with open('xml.properties', 'r') as rf:
    print('xml.properties:')
    print(javaproperties.load_xml(rf))

test ouptut

raceback (most recent call last):
  File "jp.py", line 11, in <module>
    javaproperties.dump_xml(properties, wf, sort_keys=True)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/javaproperties/xmlprops.py", line 109, in dump_xml
    print('<?xml version="1.0" encoding={0} standalone="no"?>'
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 378, in write
    self.stream.write(data)
TypeError: write() argument must be str, not bytes
text.properties:
{'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': 'β˜ƒ'}
xml.properties:
{'goat': '🐐', 'host:port': '127.0.0.1:80', 'key': 'value', 'snowman': 'β˜ƒ'}

javaproperties version

Name: javaproperties
Version: 0.7.0
Summary: Read & write Java .properties files
Home-page: https://github.com/jwodder/javaproperties
Author: John Thorvald Wodder II
Author-email: [email protected]
License: MIT
Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages
Requires: six
Required-by: javaproperties-cli

Thanks,
TK

Tests that dump timestamps fail due to timezone difference

When running the tests in GMT all the tests fail, for example:

_____________________ test_dump_timestamp[1473703254-#Mon Sep 12 14:00:54 EDT 2016\nkey=value\n] _____________________

ts = 1473703254, s = '#Mon Sep 12 14:00:54 EDT 2016\nkey=value\n'

    @pytest.mark.parametrize('ts,s', [
        (None, 'key=value\n'),
        (1473703254, '#Mon Sep 12 14:00:54 EDT 2016\nkey=value\n'),
        (
            datetime.fromtimestamp(1473703254),
            '#Mon Sep 12 14:00:54 EDT 2016\nkey=value\n',
        ),
        (
            datetime.fromtimestamp(1473703254, tzoffset('PDT', -25200)),
            '#Mon Sep 12 11:00:54 PDT 2016\nkey=value\n',
        ),
    ])
    def test_dump_timestamp(ts, s):
>       assert dumps({"key": "value"}, timestamp=ts) == s
E       AssertionError: assert '#Mon Sep 12 ...\nkey=value\n' == '#Mon Sep 12 1...\nkey=value\n'
E         - #Mon Sep 12 19:00:54 BST 2016
E         ?              ^       ^^
E         + #Mon Sep 12 14:00:54 EDT 2016
E         ?              ^       ^^
E           key=value

test/test_dumps.py:84: AssertionError

six should be listed as dependeny in setup.py or requirements.txt

OS: FreeBSD 11.2-RELEASE-p9 amd64/i386 (applies also for 12.0-RELEASE-p3)
Python version: 2.7.16 (applies also for 3.6.8)
javaproperties version: 0.5.1

The Python package is created in a pristine environment that has only the Python runtime and the Package "setuptools" as a basic dependency set.

When importing "javaproperties" it fails with

>>> import javaproperties Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/site-packages/javaproperties/__init__.py", line 15, in <module> from .propclass import Properties File "/usr/local/lib/python2.7/site-packages/javaproperties/propclass.py", line 2, in <module> from six import PY2, string_types ImportError: No module named six

By installing the six package the importing of "javaproperties" gives no more errors then.

Support for multilevel dict

Hi i wanted to write an ansible module using your lib, but stumbled to the issue that it for some reason doesn't support multilevel dict.

example:


properties=(''' 
--- 
aeron:
  cluster:
    dir: some/cool/text
''')

    return re.sub(r'[^\x20-\x7E]|[\\#!=:]', _esc, field)
  File "/usr/lib/python3.6/re.py", line 191, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or bytes-like object

and i'm just using this code

    import yaml
    import javaproperties

    p = yaml.load(properties)

    print(javaproperties.dumps(p))

Am i doing something wrong here? Just didn't fund any hint in the doc's that it maybe unsupported

Characters can get escaped when they should not be with javaproperties.dump(properties, file)

If we do something like:

`properties = {
'key=1': 'value = 1',
'key=2': 'value = 2',
'key=3': 'value = 3',
}

try:
with open(file, 'w') as f:
javaproperties.dump(properties, f)
except IOError as e:
print(e)`

We should be seeing the first '=' (associated with the keys) get escaped but not the second one (associated with the values), I believe (if '=' is being used as the separator). Currently, both get escaped.

ensure_ascii

I have been using this library recently and I'm really missing the feature to print non-ascii tests.

I know json library provide the option ensure_ascii to allow unicode characters.

Could you consider adding this option to the library?

I've found that if I use dump_xml or load_xml it works by playing around with encoding. So, please could you add the encoding option to dump or load ?

Thanks!

Example:

import javaproperties
a = {"key":"valΓ²r"}
javaproperties.dumps(a)

output:

#Tue Feb 18 15:43:21 CET 2020
key=val\\u00f2r

Expected output:

#Tue Feb 18 15:43:21 CET 2020
key=valΓ²r

Why escape colon and equals?

Hi. I'm wondering why you chose to escape colons and equals signs. I've read through a couple references, and haven't seen anything saying that it's required or even acceptable. Is it valid for properties files?

Thanks :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.