Python Forum
importing a config file prefixed with a dot
Thread Rating:
  • 3 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
importing a config file prefixed with a dot
#1
i want to establish a consistent scheme for config files for python program.  for programs made for unix and unix-like platforms i want to use config file names that begin with a dot character so they are hidden like other config files.  many programs have full or nearly-full programming power in the config fill and i want to have the same in the config files for programs in python.   many script written various shell languages use the source command to run the config file which give it full programming power in the shell language.  to do the same for python, the only way i see to do it is importing the config file as a module.  the first problem is that the import command does not like names that begin with a dot.  even the builtin.__import__() call fails at this.  any next ideas to try?


file .tryconfig.py:
# set some variables for a test config
foo = 36
bar = 42
file tryprogram.py:
__import__('.tryconfig',globals())
print(foo,bar)
so i try it:
Output:
lt1/forums /home/forums 4> ls -l .tryconfig.py;cat .tryconfig.py -rw-r--r-- 1 forums forums 57 Mar 24 23:11 .tryconfig.py # set some variables for a test config foo = 36 bar = 42 lt1/forums /home/forums 5> ls -l tryprogram.py;cat tryprogram.py -rw-r--r-- 1 forums forums 50 Mar 24 23:11 tryprogram.py __import__('.tryconfig',globals()) print(foo,bar) lt1/forums /home/forums 6> py3 tryprogram.py Traceback (most recent call last):   File "tryprogram.py", line 1, in <module>     __import__('.tryconfig',globals()) ImportError: No module named '.tryconfig' lt1/forums /home/forums 7> py2 tryprogram.py Traceback (most recent call last):   File "tryprogram.py", line 1, in <module>     __import__('.tryconfig',globals()) ValueError: Empty module name lt1/forums /home/forums 8>
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Hm! Why not just load a json file. It's suitable file format for such purposes.

with open('.app_settings', 'r') as conf:
    settings = json.load(conf)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
that (json) is what i do now.  i want to have a nearly full python coding capability in the config file allow the user that can code in python to use more advanced code to set data values for the config.

here is a silly example:
a = 'f' + 'o'*
b = 'bar'
ab = a + b
time_period_in_seconds = 5 * 60 * 60 # 5 hours
that last line might be a more realistic use case example.  i want to also allow comprehension, loops, i/o, etc.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Then you need some serializing method. Like pickle or dill. Dumping a class object with all its data and methods is perhaps what you need.

I've seen that you may not want to install additional modules. And I found this.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
serialization would not help as that would compromise the format of the file.  it needs to be directly editable with an editor like emacs or vi.  that basically means the file will generally have python as its content.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
Beside dot meaning relative import, import something creates variable something and variable names cant start with a dot.

You can use/abuse importlib library to load module from a file and execute it, make it importable and import it (for python 3.?+, older ones use imp?).

Example (with big help of importlib docs)
Output:
jacq /tmp> cat .boo.py print('boo') def boo():     print('boo boo')
>>> import sys
>>> import importlib.util as imput
>>> spec = imput.spec_from_file_location('boo', '.boo.py')
>>> boo_module = imput.module_from_spec(spec)
>>> spec.loader.exec_module(boo_module)
boo
>>> sys.modules['boo'] = boo_module
>>> import boo
>>> boo.boo()
boo boo
But doing such thing just to have hidden config file seems be a little exaggerated. Is not better to put your config file to some hidden directory (like ~/.config/skapeutil), modify sys.path and import it in a standard way?
Reply
#7
You could use exec:
exec(open('.config').read())
There's more on this at Stack Overflow: http://stackoverflow.com/questions/43619...n-3#437857
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
I came across this. But it uses some tricky methods like json.dump(list(bytecode)).

See jsonpickle or at least how is done. Just an example:

In [1]: import jsonpickle

In [2]: class Thing(object):
   ...:     def __init__(self, name):
   ...:         self.name = name
   ...: 
   ...: obj = Thing('Awesome')
   ...: 

In [3]: frozen = jsonpickle.encode(obj)

In [4]: frozen
Out[4]: '{"py/object": "__main__.Thing", "name": "Awesome"}'
This is from the webside
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
Instead of importing into the global namespace, why not just treat it like a module?

import some_random_config as conf

print(conf.foo)
That way, if someone else is looking at your script, they won't be totally lost about where you're defining variables, and if they make a mistake with naming, they'll get a meaningful error message (conf.foo is not defined).
Reply
#10
i can get things to work by using conf=__import__(filename) as long as there is no dot in the file name  ('.' not in filename).  avoiding config data going into globals() or locals() is a good idea for run time safety in case the user accidentally makes the config file world writable.  that exec() way was something i was thinking about.  it was what made me think i needed to do the config in a private variable space.  that would let me .pop all the variables i know about and complain about unknown variables that remain.  time to try a module/function to do it.

there is configparser.  but it assumes the windows ini format.  i'm not going to use that format.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  New2Python: Help with Importing/Mapping Image Src to Image Code in File CluelessITguy 0 729 Nov-17-2022, 04:46 PM
Last Post: CluelessITguy
  Problem with importing Python file in Visual Studio Code DXav 7 5,113 Jun-15-2022, 12:54 PM
Last Post: snippsat
  importing functions from a separate python file in a separate directory Scordomaniac 3 1,387 May-17-2022, 07:49 AM
Last Post: Pedroski55
  Updating a config file [solved] ebolisa 8 2,607 Nov-04-2021, 10:20 AM
Last Post: Gribouillis
  Importing a function from another file runs the old lines also dedesssse 6 2,570 Jul-06-2021, 07:04 PM
Last Post: deanhystad
  Is there a library for recursive object creation using config objects johsmi96 0 1,856 May-03-2021, 08:09 PM
Last Post: johsmi96
  help with pytesseract.image_to_string(savedImage, config='--psm 11')iamge to string korenron 0 2,708 Apr-29-2021, 10:08 AM
Last Post: korenron
  Importing text file into excel spreadsheet with formatting david_dsmn 1 3,633 Apr-05-2021, 10:21 PM
Last Post: david_dsmn
  Config file update Olivier74 0 1,484 Aug-18-2020, 03:36 PM
Last Post: Olivier74
  importing a CSV file into Python russoj5 1 2,965 Aug-02-2020, 12:03 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020