Am 16.11.2012 13:06, schrieb chip9munk:
I would like to use conf file to get all the variables in my code. And
it works great. I use the following (simple example):

execfile("example.conf", config)
     print config["value1"]

and it works like a charm.

This works, but in general importing configuration data by loading and executing code is a questionable approach. The problem is in particular that the code parser is always more strict with the syntax than a configuration file should be. Also, it presents the danger of code injection, especially when exec'ing or importing untrusted code.

That said, if you really want full programmability inside that configuration and are aware of the implications, you can do that. In that case, I would rather call this a Python module though and instead "from settings.py import *" to import any setting from this module (this is similar to exec(), but less hack-ish). I use something similar to import settings for automated tests, but still wouldn't recommend it for general use.

If you don't want that, use a configuration file parser instead. Python comes with one, see the section "13.2 Configuration file parser" at http://docs.python.org/2/library/, which can both read and write simple configuration files.


I should also mention that I use Python 3.. so some of the solutions I
came across are not compatible...

No you don't, Above code clearly uses a print statement instead of a print function. :P Anyhow, concerning the link above, replace the 2 with a 3 and skip to section 14.2.

Uli

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to