How to get current line of source file when processing a macro? - python

I want to pre-process C source code with jinja2 and I would like for some macros to be able to output #line lines:
#!/usr/bin/env python3
from jinja2 import *
#pass_context
def mymacro(ctx):
return '#line ?? "??"'
env = Environment()
env.globals["mymacro"] = mymacro
rr = env.from_string(
"""
// file.h
{{ mymacro() }}
"""
).render()
print(rr)
How do I get current line within mymacro global? I tried inspecting jinja2.runtime.Context, but I can't find anything helpful. Is this possible? Note that the line of macro invocation is visible when an exception is thrown - so it is stored somewhere.

This is the line that brought a solution:
template = tb.tb_frame.f_globals.get("__jinja_template__")
Source: debug.py#L55
The variable tb being a exception traceback, in this context.
And then, looking further, I realised that Jinja is using this line __jinja_template__ to frame where the template lines are in the stack of Python.
With that, and the function get_corresponding_lineno that they are using a few lines later in the debug.py file:
template = tb.tb_frame.f_globals.get("__jinja_template__")
if template is not None:
lineno = template.get_corresponding_lineno(tb.tb_lineno)
Source: debug.py#L58
It was now quite clear how to achieve it:
get the whole Python stack
loop over it until you find the template boundary
translate the current line of Python code in a line of the template with the help of get_corresponding_lineno
This gives:
#!/usr/bin/env python3
from jinja2 import *
from inspect import stack, currentframe
def mymacro():
for frameInfo in stack():
if frameInfo.frame.f_globals.get("__jinja_template__") is not None:
template = frameInfo.frame.f_globals.get("__jinja_template__")
break
return (
'#line '
f'{template.get_corresponding_lineno(currentframe().f_back.f_lineno)}'
)
env = Environment()
env.globals["mymacro"] = mymacro
rr = env.from_string(
"""
// file.h
{{ mymacro() }}
"""
).render()
print(rr)
Which prints us:
// file.h
#line 4

Related

how to write to a file with a fixed template in python?

I have a fixed template to be written which is pretty long as,
REQUEST DETAILS
RITM :: RITM1234
STASK :: TASK1234
EMAIL :: abc#abc.com
USER :: JOHN JOY
CONTENT DETAILS
TASK STATE :: OPEN
RAISED ON :: 12-JAN-2021
CHANGES :: REMOVE LOG
something like this, which would be 100 lines.
Do we have any way to store it as template or store it in files like ".toml" or similar files and write to values(right side of ::) in python?
Put all the inputs as placeholders using $ and save it as txt file.
from string import Template
t = Template(open('template.txt', 'r'))
t.substitute(params_dict)
Sample,
>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'
For template creation I use jinja :
from jinja2 import FileSystemLoader, Template
# Function creating from template files.
def write_file_from_template(template_path, output_name, template_variables, output_directory):
template_read = open(template_path).read()
template = Template(template_read)
rendered = template.render(template_variables)
output_path = os.path.join(output_directory, output_name)
output_file = open(output_path, 'w+')
output_file.write(rendered)
output_file.close()
print('Created file at %s' % output_path)
return output_path
journal_output = write_file_from_template(
template_path=template_path,
output_name=output_name,
template_variables={'file_output':file_output,
'step_size':step_size,
'time_steps':time_steps},
output_directory=output_directory)
With a file named file.extension.TEMPLATE:
# This is a new file :
{{ file_output }}
# The step size is :
{{ step_size }}
# The time steps are :
{{ time_steps }}
You may need to modify it a little bit, but the major things are there.

Sphinx - Let the customize HTML know the variable

# conf.py
language='en'
html_extra_path = ["customize.html"]
<!-- customize.html -->
{{ variables }} <!-- from the conf.py -->
{{ language }} <!-- expected output: en -->
How can I let the customize.html know the variables is from the config?
.. note:: assume the customize.html file is not in the documents of the theme.
I can do it by myself with Jinja, but this is not what I want.
I think sphinx already provides a way to do the things, does anyone know what is it?
Solution 1: modify sphinx-build.exe process
I hack the code (i.e. you could not build with sphinx-build.exe directly) to achieve it.
First, we observe sphinx-build.exe do what things.
# site-packages\Sphinx-x.x.x.dist-info\entry_points.txt
[console_scripts]
...
sphinx-build = sphinx.cmd.build:main
...
and then you know it actually calls sphinx.cmd.build:main to run,
you can reference it and make modifications to satisfying you.
For example:
import sphinx.cmd.build
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
from sphinx.cmd.build import patch_docutils, docutils_namespace, handle_exception, Sphinx
def setup_extra_html(app):
html_builder = app.builder
ctx = {attr: app.config[attr] for attr in dir(app.config) if not attr.startswith('_')}
html_builder.globalcontext = ctx.copy()
# Please put your HTML to the ``templates_path`` that you define, since it concept about the BuiltinTemplateLoader.pathchain
pagename = 'disqus_statistic' # <-- your HTML, you can set it on the conf.py and then get it with ``ctx``
templatename = f'{pagename}.html'
html_builder.handle_page(pagename=pagename, addctx=dict(), templatename=templatename, outfilename=None)
def your_build_main(*args):
...
try:
with patch_docutils(source_dir)), docutils_namespace():
app = Sphinx(...)
if isinstance(app.builder, StandaloneHTMLBuilder):
setup_extra_html(app)
app.build(force_all=False, filenames)
return app.statuscode
except (Exception, KeyboardInterrupt) as exc:
...
cmd_list = [source_dir, output_dir, '-b', 'html', ...]
sphinx.cmd.build.build_main = your_build_main # override it.
sphinx.cmd.build.main(cmd_list) # it will call sphinx.cmd.build.build_main
And now, the following contents will work as you expected.
<!-- original disqus_statistic.html -->
{%- if html_favicon %}
Test Icon
{%- endif %}
{{ language }}
you should complete the detail by yourself since the code is too long.
or you can refer my script of sphinx_cmd_build.py
Solution 2: add the plugin (extension)
tl;dr
# your_extension.py
from sphinx.application import Sphinx
from sphinx.builders.html import StandaloneHTMLBuilder
import pathlib
def expand_init_builder(app):
Sphinx._init_builder(app)
do_something(app)
def setup(app: Sphinx):
app.add_config_value('config_value_define_by_you', default='', rebuild=True)
app._init_builder = lambda: expand_init_builder(app)
def do_something(app: Sphinx):
user_config = {attr: app.config[attr] for attr in dir(app.config) if not attr.startswith('_')} # all variable of conf.py
# user_config.update(...) # Hard coding is fine, but not recommend.
user_config.update(dict(Path=pathlib.Path)) # recommend you, it's useful.
html_builder: StandaloneHTMLBuilder = app.builder
html_builder.globalcontext = user_config
html_builder.handle_page(pagename=page_name, addctx=dict(), templatename=template_name, outfilename=None)
# conf.py
# sys.path.insert(...)
extensions.append('your_extension') # Make sure your scrips can found in sys.path.
# https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-templates_path
templates_path = ['_templates/sphinx_rtd_theme'] # I hope you know what I mean... see the above link.
# I put my_html.html in ``_templates/sphinx_rtd_theme/my_html.html``
config_value_define_by_you = "https://github.com/CarsonSlovoka/typing-game"
<!-- my_html.html -->
{{ Path(config_value_define_by_you).name }} <!-- render result: typing-game -->
Long story (explain solutions2)
Sphinx-build.exe doing what things?
init # <-- and this one is not we cared.
create an instance of Sphinx(), the instance is app. i.e. app = Sphinx(...)
app.build
it calls the builder to start building, the builder format which defines by the user, in my case the build format is HTML, so its builder is StandaloneHTMLBuilder
And then, you know all files that are created by the builder.
The idea is: if we can get the builder, then we can do anything we want.
You will find the builder that is creat after the Sphinx(...),
so the solutions one, I tell you setup_extra_html after the app = Sphinx(...)
If you don't like to write these codes and think it's too complex.
The second way is to write the extensions,
the concept is the same as the above -- try to get the builder
you see the Sphinx(...) its constructor, and you find the code as below
class Sphinx:
def __init__(...):
...
# load all user-given extension modules
for extension in self.config.extensions:
self.setup_extension(extension) # <-- the extension you write
...
# create the builder
self.builder = self.create_builder(buildername) <-- this is we want
self._init_env(freshenv)
self._init_builder()
And then, you know the normal way to create the extensions which couldn't get the builder,
but you notice that if you do something after the self._init_builder() finished, then it's ok.
I provide my projects for your reference.
The real things that I want is, I want to create a page and I hope it can count the numbers of comments for each article, and show me.
You will understand, if I don't use the sphinx, but choose naming convention, then I must hard code a lot of things.
solution 1: https://github.com/CarsonSlovoka/typing-game/commit/376c9e20eac4a3c9b269b5bfbc8adb85ad9f6d36
solution 2: https://github.com/CarsonSlovoka/typing-game/commit/69411e15f1ace853edcafafc14759ba79b7ac288
demo: https://carsonslovoka.github.io/typing-game/en/doc.html#statistic -> and then, click counts of the Disqus.
original HTML
I hope you will get help and think it useful!

Is inline code allowed in Jinja templates?

I'm using Jinja on my site and I like it.
I've come across a simple need. How to display today's date? Is there a way to inline some Python code in a Jinja template?
import datetime
now = datetime.datetime.utcnow()
print now.strftime("%Y-%m-%d %H:%M")
This article says no, but suggests using a macro or a filter?
Really? Must we resort to all that? OK, what would that look like in this case?
No, there is no way to inline Python into Jinja. However, you can add to the constructs that Jinja knows by extending the Environment of the template engine or the global namespace available to all templates. Alternately, you can add a filter that let's you format datetime objects.
Flask stores the Jinja2 Environment on app.jinja_env. You can inject new context into the environment by either adding to this dictionary directly, or by using the #app.context_processor decorator.
Whatever path you choose, this should be done while you are setting up the application, before you have served any requests. (See the snippets section of the website for some good examples of how to set up filters - the docs contain a good example of adding to the global variables).
The current answers are correct for pretty much every situation. However there are some very rare cases where you would want to have python code inside the template. In my case I want to use it to preprocess some latex files and I would prefer to keep the python code generating table values, plots, etc, inside the latex file it self.
So I made a Jinja2 extension that adds a new "py" block allowing python code to be written inside the template. Please keep in mind that I had to do some questionable work-arounds to get this to work, so I'm not 100% sure in which situations it fails or behaves unexpectedly.
This is an example template.
Foo was given to the template
foo: {{ foo }}
Bar was not, so it is missing
bar is missing: {{ bar == missing }}
{% py %}
# Normal python code in here
# Excess indentation will be removed.
# All template variables are accessible and can be modified.
import numpy as np
a = np.array([1, 2])
m = np.array([[3, 4], [5, 6]])
bar = m # a * foo
# It's also possible to template the python code.
{% if change_foo %}
foo = 'new foo value'
{% endif %}
print("Stdio is redirected to the output.")
{% endpy %}
Foo will have the new value if you set change_foo to True
foo: {{ foo }}
Bar will now have a value.
bar: {{ bar }}
{% py %}
# The locals from previous blocks are accessible.
m = m**2
{% endpy %}
m:
{{ m }}
The output if we set the template parameters to foo=10, change_foo=True is:
Foo was given to the template
foo: 10
Bar was not, so it is missing
bar is missing: True
Stdio is redirected to the output.
Foo will have the new value if you set change_foo to True
foo: new foo value
Bar will now have a value.
bar: [110 170]
m:
[[ 9 16]
[25 36]]
The extension with a main function to run the example.
from jinja2 import Environment, PackageLoader, nodes
from jinja2.ext import Extension
from textwrap import dedent
from io import StringIO
import sys
import re
import ctypes
def main():
env = Environment(
loader=PackageLoader('python_spike', 'templates'),
extensions=[PythonExtension]
)
template = env.get_template('emb_py2.txt')
print(template.render(foo=10, change_foo=True))
var_name_regex = re.compile(r"l_(\d+)_(.+)")
class PythonExtension(Extension):
# a set of names that trigger the extension.
tags = {'py'}
def __init__(self, environment: Environment):
super().__init__(environment)
def parse(self, parser):
lineno = next(parser.stream).lineno
body = parser.parse_statements(['name:endpy'], drop_needle=True)
return nodes.CallBlock(self.call_method('_exec_python',
[nodes.ContextReference(), nodes.Const(lineno), nodes.Const(parser.filename)]),
[], [], body).set_lineno(lineno)
def _exec_python(self, ctx, lineno, filename, caller):
# Remove access indentation
code = dedent(caller())
# Compile the code.
compiled_code = compile("\n"*(lineno-1) + code, filename, "exec")
# Create string io to capture stdio and replace it.
sout = StringIO()
stdout = sys.stdout
sys.stdout = sout
try:
# Execute the code with the context parents as global and context vars and locals.
exec(compiled_code, ctx.parent, ctx.vars)
except Exception:
raise
finally:
# Restore stdout whether the code crashed or not.
sys.stdout = stdout
# Get a set of all names in the code.
code_names = set(compiled_code.co_names)
# The the frame in the jinja generated python code.
caller_frame = sys._getframe(2)
# Loop through all the locals.
for local_var_name in caller_frame.f_locals:
# Look for variables matching the template variable regex.
match = re.match(var_name_regex, local_var_name)
if match:
# Get the variable name.
var_name = match.group(2)
# If the variable's name appears in the code and is in the locals.
if (var_name in code_names) and (var_name in ctx.vars):
# Copy the value to the frame's locals.
caller_frame.f_locals[local_var_name] = ctx.vars[var_name]
# Do some ctypes vodo to make sure the frame locals are actually updated.
ctx.exported_vars.add(var_name)
ctypes.pythonapi.PyFrame_LocalsToFast(
ctypes.py_object(caller_frame),
ctypes.c_int(1))
# Return the captured text.
return sout.getvalue()
if __name__ == "__main__":
main()
You can add to global variables which can be accessed from Jinja templates. You can put your own function definitions in there, which do whatever you need.

For loop is 'printed' every time I hit refresh

I build simple webpage using CherryPy and Jinja2
The webserver python file:
import cherrypy
from jinja2 import Environment, FileSystemLoader
from soltyslib import listFiles
env = Environment(loader=FileSystemLoader('templates'))
class HelloWorld(object):
#cherrypy.expose
def index(self):
template = env.get_template('index.html')
result = template.render(name='Pawel',files=listFiles('templates'))
return result
cherrypy.quickstart(HelloWorld())
Template file:
Hello {{name}}!
<ul>
{% for file in files %}
<li>{{file}}</li>
{% endfor %}
</ul>
Ok, and then I run webserver, I go to 127.0.0.1:8080 and see result that is expected:
Hello Pawel!
templates\index.html
templates\list.html
But then I hit refresh in browser and this is a result:
Hello Pawel!
templates\index.html
templates\list.html
templates\index.html
templates\list.html
Why? for loop is evaluated again? How to prevent from doing so?
And in case somebody wondering how listFiles function looks:
import os,sys
from collections import deque
def listFiles(cdir, fileslist=[]):
basedir = cdir
queuedir = deque()
queuedir.append(basedir)
while len(queuedir) > 0:
currentbase = queuedir.popleft()
for f in os.listdir(currentbase):
f = os.path.join(currentbase,f)
if os.path.isdir(f):
queuedir.append(f)
else:
fileslist.append(f)
return fileslist
Your problem is
def listFiles(cdir, fileslist=[]):
You're reusing the same list on every call, because default arguments are evaluated only when the function is defined, not every time it's called. See "Least Astonishment" and the Mutable Default Argument for a long discussion if this behavior.
Do
def listFiles(cdir, fileslist=None):
if fileslist is None:
fileslist = []
Your problem is in fileslist=[] in the function declaration. Default values are only ever evaluated once, which means that the list is created the first call, but never rebuilt or cleared.
It's the default kwarg for fileslist in listFiles. That list is created once at module load time and keeps accruing items as you append.

Properties file in python (similar to Java Properties)

Given the following format (.properties or .ini):
propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNameN=propertyValueN
For Java there is the Properties class that offers functionality to parse / interact with the above format.
Is there something similar in python's standard library (2.x) ?
If not, what other alternatives do I have ?
I was able to get this to work with ConfigParser, no one showed any examples on how to do this, so here is a simple python reader of a property file and example of the property file. Note that the extension is still .properties, but I had to add a section header similar to what you see in .ini files... a bit of a bastardization, but it works.
The python file: PythonPropertyReader.py
#!/usr/bin/python
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')
print config.get('DatabaseSection', 'database.dbname');
The property file: ConfigFile.properties
[DatabaseSection]
database.dbname=unitTest
database.user=root
database.password=
For more functionality, read: https://docs.python.org/2/library/configparser.html
For .ini files there is the configparser module that provides a format compatible with .ini files.
Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).
I know that this is a very old question, but I need it just now and I decided to implement my own solution, a pure python solution, that covers most uses cases (not all):
def load_properties(filepath, sep='=', comment_char='#'):
"""
Read the file passed as parameter as a properties file.
"""
props = {}
with open(filepath, "rt") as f:
for line in f:
l = line.strip()
if l and not l.startswith(comment_char):
key_value = l.split(sep)
key = key_value[0].strip()
value = sep.join(key_value[1:]).strip().strip('"')
props[key] = value
return props
You can change the sep to ':' to parse files with format:
key : value
The code parses correctly lines like:
url = "http://my-host.com"
name = Paul = Pablo
# This comment line will be ignored
You'll get a dict with:
{"url": "http://my-host.com", "name": "Paul = Pablo" }
A java properties file is often valid python code as well. You could rename your myconfig.properties file to myconfig.py. Then just import your file, like this
import myconfig
and access the properties directly
print myconfig.propertyName1
if you don't have multi line properties and a very simple need, a few lines of code can solve it for you:
File t.properties:
a=b
c=d
e=f
Python code:
with open("t.properties") as f:
l = [line.split("=") for line in f.readlines()]
d = {key.strip(): value.strip() for key, value in l}
If you have an option of file formats I suggest using .ini and Python's ConfigParser as mentioned. If you need compatibility with Java .properties files I have written a library for it called jprops. We were using pyjavaproperties, but after encountering various limitations I ended up implementing my own. It has full support for the .properties format, including unicode support and better support for escape sequences. Jprops can also parse any file-like object while pyjavaproperties only works with real files on disk.
This is not exactly properties but Python does have a nice library for parsing configuration files. Also see this recipe: A python replacement for java.util.Properties.
i have used this, this library is very useful
from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print(p)
print(p.items())
print(p['name3'])
p['name3'] = 'changed = value'
Here is link to my project: https://sourceforge.net/projects/pyproperties/. It is a library with methods for working with *.properties files for Python 3.x.
But it is not based on java.util.Properties
This is a one-to-one replacement of java.util.Propeties
From the doc:
def __parse(self, lines):
""" Parse a list of lines and create
an internal property dictionary """
# Every line in the file must consist of either a comment
# or a key-value pair. A key-value pair is a line consisting
# of a key which is a combination of non-white space characters
# The separator character between key-value pairs is a '=',
# ':' or a whitespace character not including the newline.
# If the '=' or ':' characters are found, in the line, even
# keys containing whitespace chars are allowed.
# A line with only a key according to the rules above is also
# fine. In such case, the value is considered as the empty string.
# In order to include characters '=' or ':' in a key or value,
# they have to be properly escaped using the backslash character.
# Some examples of valid key-value pairs:
#
# key value
# key=value
# key:value
# key value1,value2,value3
# key value1,value2,value3 \
# value4, value5
# key
# This key= this value
# key = value1 value2 value3
# Any line that starts with a '#' is considerered a comment
# and skipped. Also any trailing or preceding whitespaces
# are removed from the key/value.
# This is a line parser. It parses the
# contents like by line.
You can use a file-like object in ConfigParser.RawConfigParser.readfp defined here -> https://docs.python.org/2/library/configparser.html#ConfigParser.RawConfigParser.readfp
Define a class that overrides readline that adds a section name before the actual contents of your properties file.
I've packaged it into the class that returns a dict of all the properties defined.
import ConfigParser
class PropertiesReader(object):
def __init__(self, properties_file_name):
self.name = properties_file_name
self.main_section = 'main'
# Add dummy section on top
self.lines = [ '[%s]\n' % self.main_section ]
with open(properties_file_name) as f:
self.lines.extend(f.readlines())
# This makes sure that iterator in readfp stops
self.lines.append('')
def readline(self):
return self.lines.pop(0)
def read_properties(self):
config = ConfigParser.RawConfigParser()
# Without next line the property names will be lowercased
config.optionxform = str
config.readfp(self)
return dict(config.items(self.main_section))
if __name__ == '__main__':
print PropertiesReader('/path/to/file.properties').read_properties()
If you need to read all values from a section in properties file in a simple manner:
Your config.properties file layout :
[SECTION_NAME]
key1 = value1
key2 = value2
You code:
import configparser
config = configparser.RawConfigParser()
config.read('path_to_config.properties file')
details_dict = dict(config.items('SECTION_NAME'))
This will give you a dictionary where keys are same as in config file and their corresponding values.
details_dict is :
{'key1':'value1', 'key2':'value2'}
Now to get key1's value :
details_dict['key1']
Putting it all in a method which reads that section from config file only once(the first time the method is called during a program run).
def get_config_dict():
if not hasattr(get_config_dict, 'config_dict'):
get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
return get_config_dict.config_dict
Now call the above function and get the required key's value :
config_details = get_config_dict()
key_1_value = config_details['key1']
-------------------------------------------------------------
Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = dict()
for section in config.sections():
get_config_section.section_dict[section] =
dict(config.items(section))
return get_config_section.section_dict
To access:
config_dict = get_config_section()
port = config_dict['DB']['port']
(here 'DB' is a section name in config file
and 'port' is a key under section 'DB'.)
create a dictionary in your python module and store everything into it and access it, for example:
dict = {
'portalPath' : 'www.xyx.com',
'elementID': 'submit'}
Now to access it you can simply do:
submitButton = driver.find_element_by_id(dict['elementID'])
My Java ini files didn't have section headers and I wanted a dict as a result. So i simply injected an "[ini]" section and let the default config library do its job.
Take a version.ini fie of the eclipse IDE .metadata directory as an example:
#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800
# 'injected' ini section
[ini]
#Mon Dec 20 07:35:29 CET 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.19.0.v20210303-1800
The result is converted to a dict:
from configparser import ConfigParser
#staticmethod
def readPropertyFile(path):
# https://stackoverflow.com/questions/3595363/properties-file-in-python-similar-to-java-properties
config = ConfigParser()
s_config= open(path, 'r').read()
s_config="[ini]\n%s" % s_config
# https://stackoverflow.com/a/36841741/1497139
config.read_string(s_config)
items=config.items('ini')
itemDict={}
for key,value in items:
itemDict[key]=value
return itemDict
This is what I'm doing in my project: I just create another .py file called properties.py which includes all common variables/properties I used in the project, and in any file need to refer to these variables, put
from properties import *(or anything you need)
Used this method to keep svn peace when I was changing dev locations frequently and some common variables were quite relative to local environment. Works fine for me but not sure this method would be suggested for formal dev environment etc.
import json
f=open('test.json')
x=json.load(f)
f.close()
print(x)
Contents of test.json:
{"host": "127.0.0.1", "user": "jms"}
I have created a python module that is almost similar to the Properties class of Java ( Actually it is like the PropertyPlaceholderConfigurer in spring which lets you use ${variable-reference} to refer to already defined property )
EDIT : You may install this package by running the command(currently tested for python 3).
pip install property
The project is hosted on GitHub
Example : ( Detailed documentation can be found here )
Let's say you have the following properties defined in my_file.properties file
foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge
Code to load the above properties
from properties.p import Property
prop = Property()
# Simply load it into a dictionary
dic_prop = prop.load_property_files('my_file.properties')
Below 2 lines of code shows how to use Python List Comprehension to load 'java style' property file.
split_properties=[line.split("=") for line in open('/<path_to_property_file>)]
properties={key: value for key,value in split_properties }
Please have a look at below post for details
https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/
you can use parameter "fromfile_prefix_chars" with argparse to read from config file as below---
temp.py
parser = argparse.ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument('--a')
parser.add_argument('--b')
args = parser.parse_args()
print(args.a)
print(args.b)
config file
--a
hello
--b
hello dear
Run command
python temp.py "#config"
You could use - https://pypi.org/project/property/
eg - my_file.properties
foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge
long = a very long property that is described in the property file which takes up \
multiple lines can be defined by the escape character as it is done here
url=example.com/api?auth_token=xyz
user_dir=${HOME}/test
unresolved = ${HOME}/files/${id}/${bar}/
fname_template = /opt/myapp/{arch}/ext/{objid}.dat
Code
from properties.p import Property
## set use_env to evaluate properties from shell / os environment
prop = Property(use_env = True)
dic_prop = prop.load_property_files('my_file.properties')
## Read multiple files
## dic_prop = prop.load_property_files('file1', 'file2')
print(dic_prop)
# Output
# {'foo': 'I am awesome', 'bar': 'fudge-bar', 'chocolate': 'fudge',
# 'long': 'a very long property that is described in the property file which takes up multiple lines
# can be defined by the escape character as it is done here', 'url': 'example.com/api?auth_token=xyz',
# 'user_dir': '/home/user/test',
# 'unresolved': '/home/user/files/${id}/fudge-bar/',
# 'fname_template': '/opt/myapp/{arch}/ext/{objid}.dat'}
I did this using ConfigParser as follows. The code assumes that there is a file called config.prop in the same directory where BaseTest is placed:
config.prop
[CredentialSection]
app.name=MyAppName
BaseTest.py:
import unittest
import ConfigParser
class BaseTest(unittest.TestCase):
def setUp(self):
__SECTION = 'CredentialSection'
config = ConfigParser.ConfigParser()
config.readfp(open('config.prop'))
self.__app_name = config.get(__SECTION, 'app.name')
def test1(self):
print self.__app_name % This should print: MyAppName
This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify
hg:d
-h or --help print usage summary
-c Specify char that identifies comment
-s Separator between key and value in prop file
and specify properties file that needs to be parsed eg : python
EnvParamSet.py -c # -s = env.properties
import pipes
import sys , getopt
import os.path
class Parsing :
def __init__(self , seprator , commentChar , propFile):
self.seprator = seprator
self.commentChar = commentChar
self.propFile = propFile
def parseProp(self):
prop = open(self.propFile,'rU')
for line in prop :
if line.startswith(self.commentChar)==False and line.find(self.seprator) != -1 :
keyValue = line.split(self.seprator)
key = keyValue[0].strip()
value = keyValue[1].strip()
print("export %s=%s" % (str (key),pipes.quote(str(value))))
class EnvParamSet:
def main (argv):
seprator = '='
comment = '#'
if len(argv) is 0:
print "Please Specify properties file to be parsed "
sys.exit()
propFile=argv[-1]
try :
opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
except getopt.GetoptError,e:
print str(e)
print " possible arguments -s <key value sperator > -c < comment char > <file> \n Try -h or --help "
sys.exit(2)
if os.path.isfile(args[0])==False:
print "File doesnt exist "
sys.exit()
for opt , arg in opts :
if opt in ("-h" , "--help"):
print " hg:d \n -h or --help print usage summary \n -c Specify char that idetifes comment \n -s Sperator between key and value in prop file \n specify file "
sys.exit()
elif opt in ("-s" , "--seprator"):
seprator = arg
elif opt in ("-c" , "--comment"):
comment = arg
p = Parsing( seprator, comment , propFile)
p.parseProp()
if __name__ == "__main__":
main(sys.argv[1:])
Lightbend has released the Typesafe Config library, which parses properties files and also some JSON-based extensions. Lightbend's library is only for the JVM, but it seems to be widely adopted and there are now ports in many languages, including Python: https://github.com/chimpler/pyhocon
You can use the following function, which is the modified code of #mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.
def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
"""
Reads a .properties file and returns the key value pairs as dictionary.
if key value is specified, then it will return its value alone.
"""
with open(propertiesFile) as f:
l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
d = {key.strip(): value.strip() for key, value in l}
if key:
return d[key]
else:
return d
this works for me.
from pyjavaproperties import Properties
p = Properties()
p.load(open('test.properties'))
p.list()
print p
print p.items()
print p['name3']
I followed configparser approach and it worked quite well for me. Created one PropertyReader file and used config parser there to ready property to corresponding to each section.
**Used Python 2.7
Content of PropertyReader.py file:
#!/usr/bin/python
import ConfigParser
class PropertyReader:
def readProperty(self, strSection, strKey):
config = ConfigParser.RawConfigParser()
config.read('ConfigFile.properties')
strValue = config.get(strSection,strKey);
print "Value captured for "+strKey+" :"+strValue
return strValue
Content of read schema file:
from PropertyReader import *
class ReadSchema:
print PropertyReader().readProperty('source1_section','source_name1')
print PropertyReader().readProperty('source2_section','sn2_sc1_tb')
Content of .properties file:
[source1_section]
source_name1:module1
sn1_schema:schema1,schema2,schema3
sn1_sc1_tb:employee,department,location
sn1_sc2_tb:student,college,country
[source2_section]
source_name1:module2
sn2_schema:schema4,schema5,schema6
sn2_sc1_tb:employee,department,location
sn2_sc2_tb:student,college,country
You can try the python-dotenv library. This library reads key-value pairs from a .env (so not exactly a .properties file though) file and can set them as environment variables.
Here's a sample usage from the official documentation:
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.

Categories

Resources