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
#15
not withstanding this error in python3 , i made this module:

!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
"""Process a config file in Python format

file          pyconf.py
purpose       process a config file in python format
email         10054452614123394844460370234029112340408691

The intent is that this command works correctly under both Python 2 and
Python 3.  Please report failures or code improvement to the author.
"""

__license__ = """
Copyright (C) 2017, by Phil D. Howard - all other rights reserved

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

The author may be contacted by decoding the number
10054452614123394844460370234029112340408691
(provu igi la numeron al duuma)
"""

import os, pwd
from sys import argv, stderr, stdout, version_info

if version_info.major<3:
    ints=(int,long)
    strs=(str,unicode,)
else:
    ints=(int,)
    strs=(str,bytes,bytearray,)

def pyconf(*args,**opts):
    if len(args)>0:
        m='positional arguments are not used: '
        m+=', '.join([repr(a) for a in args])
        raise Exception(m)
    uid=opts.pop('uid',os.getuid())
    home=opts.pop('home',pwd.getpwuid(uid).pw_dir)
    maxsize=opts.pop('maxsize',1048576)
    if 'path' in opts:
        p=opts['path']
    else:
        p=home
        if 'dotdir' in opts:
            p += '/.' + opts.pop('dotdir')
        if 'subdir' in opts:
            p += '/' + opts.pop('subdir')
        p += '/' + opts.pop('name')
        if len(opts)>0:
            m='unknown option'
            if len(opts)>1:
                m+='s'
            m+=': '+', '.join([str(n)+'='+repr(v) for n,v in opts.items()])
            raise Exception(m)
    with open(p) as f:
        s=f.read(maxsize+1)
    if len(s)>maxsize:
        m='config file {} size is larger than {}'
        raise Exception(m.format(repr(p),repr(maxsize)))
    c={}
    print(s)
    exec(s,{},c)
    return c

def main(args):
    """main"""
    # config file is ~/.config/foo/bar.conf
    config = pyconf(dotdir='config',subdir='foo',name='bar.conf')
    for n,v in sorted(config.items()):
        print(repr(n),'=',repr(v))
    return config.pop('status',3)

if __name__ == '__main__':
    try:
        result=main(argv)
        stdout.flush()
    except KeyboardInterrupt:
        print('')
        result=99
    except IOError:
        result=98
    if result is 0 or result is None or result is True:
        exit(0)
    if result is 1 or result is False:
        exit(1)
    if isinstance(result,strs):
        print(result,file=stderr)
        exit(1)
    try:
        exit(int(result))
    except ValueError:
        print(str(result),file=stderr)
    except TypeError:
        exit(127)
# EOF
and made this silly config file at "~/.config/foo/bar.conf" ... that fails in python3 ... and works in python2

foo = 1
for n in range(10):
    locals()['foo'+str(n)+'bar'] = [n**m for m in range(9)]
bar = 0
i have not studied exceptions enough, yet, to know the best to use for exceptions i have the pyconf() function raise.  feedback about that is sought.
Tradition is peer pressure from dead people

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


Messages In This Thread
RE: importing a config file prefixed with a dot - by Skaperen - Mar-27-2017, 07:42 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  New2Python: Help with Importing/Mapping Image Src to Image Code in File CluelessITguy 0 782 Nov-17-2022, 04:46 PM
Last Post: CluelessITguy
  Problem with importing Python file in Visual Studio Code DXav 7 5,528 Jun-15-2022, 12:54 PM
Last Post: snippsat
  importing functions from a separate python file in a separate directory Scordomaniac 3 1,485 May-17-2022, 07:49 AM
Last Post: Pedroski55
  Updating a config file [solved] ebolisa 8 2,729 Nov-04-2021, 10:20 AM
Last Post: Gribouillis
  Importing a function from another file runs the old lines also dedesssse 6 2,703 Jul-06-2021, 07:04 PM
Last Post: deanhystad
  Is there a library for recursive object creation using config objects johsmi96 0 1,909 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,774 Apr-29-2021, 10:08 AM
Last Post: korenron
  Importing text file into excel spreadsheet with formatting david_dsmn 1 3,725 Apr-05-2021, 10:21 PM
Last Post: david_dsmn
  Config file update Olivier74 0 1,537 Aug-18-2020, 03:36 PM
Last Post: Olivier74
  importing a CSV file into Python russoj5 1 3,010 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