read_conf.py :  » Business-Application » hylaPEx » hylapex » library » ftp » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Business Application » hylaPEx 
hylaPEx » hylapex » library » ftp » read_conf.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

import imp, os, sys, codecs, tempfile
import ctypes as C

def main_is_frozen():
   return (hasattr(sys, "frozen") or # new py2exe
           hasattr(sys, "importers") # old py2exe
           or imp.is_frozen("__main__")) # tools/freeze

def get_main_dir():
   if main_is_frozen():
       return os.path.dirname(sys.executable)
   return os.path.dirname(sys.argv[0])

import string, os, sys, string

#from cfgparser.compat import RawConfigParser as RCP
from ConfigParser import RawConfigParser
from ConfigParser import DuplicateSectionError
from types import DictType
import regManage
if sys.platform == 'win32':
    import _winreg as reg

company = 'unipex'
file_name_path = 'hylapex_path'
file_name_soft = 'software.unipex'
descr_company = 'Software made by Unipex srl. www.unipex.it'

class pref:
    #This class is not completed -> to do
    #Used for retrive the infomation
    def __init__(self, softname, dir_exe = '', env_user = ''):

        self.softname = softname
        
        #Problems with the rights!
        self._problem_no_rights = False

        if sys.platform.startswith("win"):
            self.reg = _reg(self.softname, env_user)
            #No registry keys found, create it -> only first use
            if self.reg.exist():
                self.pref_dir = self.get_my_path_conf()

                if self.reg.create(dir_exe, self.pref_dir) == 10:
                    self._problem_no_rights = True
            else:
                self.pref_dir = self.reg.get_path_conf()

        else:
            self.pref_dir = self.get_my_path_conf()

        for d in (self.pref_dir, os.path.join(dir_exe, 'tmp')):
            if not os.path.exists(d):
                try:
                    os.makedirs(d)
                except OSError:
                    if not env_user:
                        raise
        if not sys.platform.startswith("win"):
            self.set(dir_exe)
        #f.close()

    def get_my_path(self):
        if sys.platform.startswith('win'):
            if not self._problem_no_rights:
                path = self.reg.read_all()[self.softname]['path']
            else:
                path = get_main_dir()

        else:
            f = file(os.path.join(self.pref_dir, file_name_path), 'r')
            path = f.readlines()[0].strip()
            f.close()

        return path
    
    def get_local_temp(self):
        """
        """
        if sys.platform.startswith("win"):
            pt = os.path.join(self.get_local_settings("Local Settings"), "Temp")
        else:
            pt = tempfile.gettempdir()
        
        pt = os.path.join(pt, "hylapex")
        if not os.path.exists(pt):
            os.makedirs(pt)
        return pt

    def _get_vista_conf(self):
        """ Return the vista conf path with the new
            SHGetKnownFolderPath functions.
        """
        pSavePath = C.c_wchar_p()
        lib = C.windll.shell32

        class GUID(C.Structure):
            _fields_ = [("Data1", C.c_ulong),
                       ("Data2", C.c_ushort),
                       ("Data3", C.c_ushort),
                       ("Data4", C.c_ubyte *8), ]
        #folder_local_data
        fld = GUID()
        fld.Data1 = 0xF1B32785
        fld.Data2 = 0x6FBA
        fld.Data3 = 0x4FCF
        arr_8 = C.c_ubyte *8
        fld.Data4 = arr_8(0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91)

        ret_val = lib.SHGetKnownFolderPath(C.pointer(fld), 0,0, C.pointer(pSavePath))
        if ret_val == 0:
            return pSavePath.value
        else:
            return ""

    def get_local_settings(self, key_reg=None):
        """ Return local settings from the registry
        """
        local_settings = ""
        if not key_reg:
           key_reg = "AppData"
        if sys.platform.startswith("win"):
            key = regManage.Registry.open('HKEY_CURRENT_USER',
              "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
            for i in key.values():
                if i[0] == key_reg:
                    local_settings = i[1]
                    break
            else:
                #no path found. Are us on vista?
                local_settings = self._get_vista_conf()

            key.close()

        else:
            local_settings = self.get_my_path()

        return local_settings

    def get_pref_dir_rights(self):
        """ Return default user folder from the registry
        """
        return os.path.join(self.get_local_settings(), company, self.softname)


    def get_my_path_conf(self):
        if sys.platform == 'win32':
            if self.reg.exist():
                if sys.getwindowsversion()[0] >= 5:
                    pref_dir = self.get_pref_dir_rights()
                else:
                    pref_dir = os.environ['WINDIR']

            else:
                pref_dir = self.reg.read_all()[self.softname]['path_conf']
        else:
            dir_ = os.environ['HOME']
            pref_dir = os.path.join(dir_, '.' + company, self.softname)
        
        return pref_dir

    def set(self, path):
        f_name = os.path.join(self.pref_dir, file_name_path)
        if not os.path.exists(f_name):
            f = file(f_name, 'w')
            f.write(path + '\n')
            f.close()
            
class _reg:
    def __init__(self, soft, env_user):
        #Global variables
        self.soft = soft
        self.env_user = env_user
        self.regkey = 'software\\unipex\\'
        self.regsoft = self.regkey + self.soft
        self.hkey_u = reg.HKEY_CURRENT_USER
        self.hkey_m = reg.HKEY_LOCAL_MACHINE
        self.WV = sys.getwindowsversion()[3]; self.W98 = 1
        
        if env_user:
            #try:
                self.user = os.environ[env_user]
            #except:
            #    if self.WV != self.W98:
            #        self.user = os.environ['USERNAME']
        else:
            if self.WV != self.W98:
                self.user = os.environ['USERNAME']
                
    def exist(self):
        try:
            if not self.env_user:
                self.h_obj_u = reg.OpenKey(self.hkey_u, self.regsoft)
            self.h_obj_m = reg.OpenKey(self.hkey_m, self.regsoft)
            if self.WV != self.W98:
                reg.QueryValueEx(self.h_obj_m, 'path_conf_%s' % self.user)
            return 0
        except EnvironmentError:
            return 1

    def _open(self):
        if not self.exist():
            if self.WV == self.W98 or (self.WV != self.W98 and not self.env_user):
                self.h_obj_u = reg.OpenKey(self.hkey_u, self.regkey)
                self.k_obj_u = reg.OpenKey(self.hkey_u, self.regsoft)
            self.h_obj_m = reg.OpenKey(self.hkey_m, self.regkey)
            self.k_obj_m = reg.OpenKey(self.hkey_m, self.regsoft)

    def create(self, path, path_conf, version = ''):
        self.version = version
        self.path = path
        self.path_conf = path_conf
        self.add_key('info', self.soft, self.hkey_u)
        self.add_key('info', self.soft, self.hkey_m)
        self.h_obj_u = reg.OpenKey(self.hkey_u, self.regsoft, 0, reg.KEY_SET_VALUE)

        # -- Rights modify -- #
        try:
            self.h_obj_m = reg.OpenKey(self.hkey_m, self.regsoft, 0, reg.KEY_SET_VALUE)
        except WindowsError:
            return 10
        # ------------------- #
        self.register('info', descr_company, self.h_obj_u)
        self.register('version', self.version, self.h_obj_u)
        if self.WV != self.W98:
            self.register('path_conf_%s' % self.user, self.path_conf, self.h_obj_m)
        else:
            self.register('path_conf', self.path_conf, self.h_obj_u)
        self.register('path', self.path, obj=self.h_obj_m)
        
        return None

    def get_path_conf(self):
        return self.read_all()[self.soft]['path_conf']

    def read_all(self):
        self._open()
        vals_dict = dict()
        if not self.env_user:
            self.__read_user(vals_dict)
        self.__read_machine(vals_dict)
        if self.WV == self.W98:
            tmp_dict = dict()
            self.__read_user(tmp_dict)
            for val in tmp_dict[self.soft].keys():
                vals_dict[self.soft][val] = tmp_dict[self.soft][val]
        return vals_dict
    
    def __read_user(self, vals_dict):
        tmp = 0
        while 1:
            vals_dict2 = {}
            try:
                key = reg.EnumKey(self.h_obj_u, tmp)
                h_obj_u = reg.OpenKey(self.hkey_u, self.regkey + key) 
                vals_dict2['version'] = str(reg.QueryValueEx(h_obj_u, 'version')[0])
                if self.WV == self.W98:
                    vals_dict2['path_conf'] = str(reg.QueryValueEx(h_obj_u, 'path_conf')[0])
                tmp += 1
            except EnvironmentError, ex:
                break
            vals_dict[key] = vals_dict2

    def __read_machine(self, vals_dict):
        tmp = 0
        while 1:
            try:
                vals_dict2 = {}
                key = reg.EnumKey(self.h_obj_m, tmp)
                h_obj_m = reg.OpenKey(self.hkey_m, self.regkey + key)
                if self.WV != self.W98:
                    vals_dict2['path_conf'] = str(reg.QueryValueEx(h_obj_m, 'path_conf_%s' % self.user)[0])
                vals_dict2['path'] = str(reg.QueryValueEx(h_obj_m, 'path')[0])
                tmp += 1
            except EnvironmentError, ex:
                break
            vals_dict[key] = vals_dict2


    def register(self,type,val,obj):
        # -- Luca's modify -- #
        try:
            reg.SetValueEx(obj,type,0,reg.REG_SZ, val)
        except WindowsError:
            pass
        # ------------------- #

    def add_key(self, key, value, k):
        # -- Luca's modify -- #
        try:
            reg_obj = reg.CreateKey(k, self.regsoft)
            reg.SetValueEx(reg_obj,key,0,reg.REG_SZ,value)
        except WindowsError:
            pass
        # ------------------- #

    def close(self, obj):
        reg.CloseKey(obj)
        

class conf(object):
    def __init__(self, file_conf, key, val):
        self.key = key
        self.key_num = len(key)
        self.file = file_conf
        self.dic = {}
        if val == '':
            self.val = []
            for values in key:
                self.val.append('')
        else:
            self.val = val
    def exist(self):
        try:
            f = codecs.open(self.file, 'r', encoding="utf8", errors="replace")
            return 0
        except:         
            return 1
        
    def write(self, key, val=''):
        f = codecs.open(self.file, 'w', encoding="utf8", errors="replace")
        if type(key) is DictType:
            for values in key.keys():
                f.write(str(values) + '=' + str(key[values]) + '\n')
            f.close()
        else:
            for values in range(len(key)):
                f.write(str(key[values]) + '=' + str(val[values]) + '\n')
            
            f.close()
    def read(self):
        try:
            f = codecs.open(self.file, 'r', encoding="utf8", errors="replace")
        except:         
            self.write(self.key,self.val)
        f = codecs.open(self.file, 'r', encoding="utf8", errors="replace")
        lines = f.readlines()
        for val in lines:
            if val[:1] == '#': continue
            eg = string.find(val,'=')                         #Cerca i vari =
            if eg == -1:continue
            val_sx = val[:eg]
            if val_sx[-1:] == ' ':
                val_sx = val_sx[:-1]

            if val[eg:eg+2] == '= ':
                val_dx = val[eg + 2:]
            else:
                val_dx = val[eg + 1:]
            val_dx = val_dx.strip()
            if self.dic.has_key(val_sx):
                tmp_num = 1
                while 1:
                    if not self.dic.has_key(val_sx + str(tmp_num)):
                        break
                    else:
                        tmp_num += 1
                self.dic[val_sx + str(tmp_num)] = val_dx
            else:
                self.dic[val_sx] = val_dx                   #Richiama i valori e ins nel dizionario
        f.close()
        return self.dic                                     # Dizionario


class conf_parser(RCP):
    def __init__(self, f, section):
        """
        """
        RCP.__init__(self)
        #super(conf_parser, self).__init__()
        self.section = section
        self.file = f
        self.read =  0   
    
    def __call__(self, opt, sec='', default=0):
        """
        """
        return self.get(opt, sec, default)
    
    #My methods
    def exist(self, try_load=1):
        self.read = 1
        if os.path.exists(self.file):
            if try_load:
                RCP.read(self, self.file)
            return 0
        else:
            return 1
    def init_sections(self, sect):
        #We accepet list or dict
        if isinstance(sect, basestring):
            sect = [sect]
        for i in sect:
            # -- Luca's modify -- #
            try:
                RCP.add_section(self, i)
            except DupSec:
                pass
            # ------------------- #
    
    def init_vals(self, vals, sec = ''):
        try:
            sect = self.__have_sect(sec)
        except self.NoSection:
            self.init_sections([self.section])
            sect = self.__have_sect(sec)
        for key, val in vals.iteritems():
            RCP.set(self, sect, key, val)
    
    def exit(self):
        if not self.read:
            self.exist()
        f = codecs.open(self.file, 'w', encoding="utf8", errors="replace")
        RCP.write(self, f)
        f.close()
    
    def get_items_dict(self, sec = '', default=True):
        """ Return the options into a dict. If default are True, also the default
        """
        if not default:
            d = self.defaults()
        else:
            d = {}
        
        d_data = dict( (k, v) for k,v in self.items(sec))
        #delete the defaults values if need
        for k in d:
            del d_data[k]
        
        return d_data
    
    def set_dict(self, vals, sec = ''):
        #Set the options from a dict
        for k, val in vals.iteritems():
            if isinstance(val, bool): val = int(val)
            self.set(k, val, sec)
            
    #Defaults methods
    def options(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.options(self, sect)
    def has_option(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.has_option(self, sect, opt)
    def items(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.items(self, sect)
    def set(self, opt, val, sec = ''):
        sect = self.__have_sect(sec)
        val = str(val)
        return RCP.set(self, sect, opt, val)
    def get(self, opt, sec = '', default=0):
        if default:
            if not self.has_option(opt):
                return 'No key found: %s . Err 314 - read_conf' % opt
            else:
                return CtrlString(RCP.defaults(self)[opt])
        try:
            sect = self.__have_sect(sec)
        except self.NoSection:
            return 'No section %s found. Err 320 - read_conf' % sec

        if RCP.has_option(self, sect, opt):
            return CtrlString(RCP.get(self, sect, opt))
        else:
            return 'No key found: %s , Err 325 - read_conf' % opt

    def getint(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        if RCP.has_option(self, sect, opt):
            if not self.get(opt, sect):
                return 0
            else:
                val = self.get(opt, sect)
                if isinstance(val, basestring) and val.lower() in ("true", "yes"):
                    return 1
                elif isinstance(val, basestring) and val.lower() in ("false", "no"):
                    return 0
                else:
                    return int(float(val))
        else:
            return 0
    
    def getList(self, opt, sect='', sep=','):
        #return the values separed by sep
        value = self.get(opt, sect)
        for v in "[]()":
            value = value.replace(v, "")
        return [ x.strip() for x in value.split(sep) ]
        
        
    def remove_option(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.remove_option(self, sect, opt)
    def remove_section(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.remove_section(self, sect)

    #Utils method
    def __have_sect(self, section):
        if section: 
            sect = section
        else:
            sect = self.section
        if not RCP.has_section(self, sect):
            raise self.NoSection("%s. Here I have %s" % (sect, self.sections()))
        return sect

    class NoSection(Exception):
        def __init__(self, val):
            self.val = val
        def __str__(self):
            return repr(self.val)

class conf_parser_old(RCP):
    def __init__(self, f, section):
        RCP.__init__(self)
        self.section = section
        self.file = f
        self.read =  0   
        #My methods
    def exist(self):
        self.read = 1
        if os.path.exists(self.file):
            RCP.read(self, self.file)
            return 0
        else:
            return 1
    def init_sections(self, sect):
        #We accepet list or dict
        for i in sect:
            # -- Luca's modify -- #
            try:
                RCP.add_section(self, i)
            except DupSec:
                pass
            # ------------------- #
    def init_vals(self, vals, sec = ''):
        try:
            sect = self.__have_sect(sec)
        except NoSec:
            self.init_sections([self.section])
            sect = self.__have_sect(sec)
        for val in vals.keys():
            RCP.set(self, sect, val, vals[val])
    def exit(self):
        if not self.read:
            self.exist()
        f = codecs.open(self.file, 'w', encoding="utf8", errors="replace")
        RCP.write(self, f)
        f.close()
    def get_items_dict(self, sec = ''):
        #Return a dict with {option: val}
        dict_vals = {}
        for vals in self.items(sec):
            dict_vals[vals[0]] = vals[1]
        return dict_vals
    
    def set_dict(self, vals, sec = ''):
        #Set the options from a dict
        for val in vals.keys():
            if type(vals[val]) == type(True):
                if vals[val] == True: self.set(val, 1, sec)
                else: self.set(val, 0, sec)
            else:
                self.set(val, vals[val], sec)
    #Defaults methods
    def options(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.options(self, sect)
    def has_option(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.has_option(self, sect, opt)
    def items(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.items(self, sect)
    def set(self, opt, val, sec = ''):
        sect = self.__have_sect(sec)
        
        return RCP.set(self, sect, opt, val)
    def get(self, opt, sec = '', default=0):
        if default:
            if not self.has_option(opt):
                return 'No key found: %s . Err 314 - read_conf' % opt
            else:
                return CtrlString(RCP.defaults(self)[opt])
        try:
            sect = self.__have_sect(sec)
        except self.NoSection:
            return 'No section %s found. Err 320 - read_conf' % sec
        
        if RCP.has_option(self, sect, opt):
            return CtrlString(RCP.get(self, sect, opt))
        else:
            return 'No key found: %s , Err 325 - read_conf' % opt

    def getint(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        if RCP.has_option(self, sect, opt):
            if not self.get(opt):
                return 0
            else:
                return int(self.get(opt))
        else:
            return 0
    def remove_option(self, opt, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.remove_option(self, sect, opt)
    def remove_section(self, sec = ''):
        sect = self.__have_sect(sec)
        return RCP.remove_section(self, sect)

    #Utils method
    def __have_sect(self, section):
        if section: 
            sect = section
        else:
            sect = self.section
        if not RCP.has_section(self, sect): 
            raise self.NoSection(sect)
        return sect

    class NoSection(Exception):
        def __init__(self, val):
            self.val = val
        def __str__(self):
            return repr(self.val)

def CtrlString(val):
    if isinstance(val, int):
        return val
    return '\n'.join( [x.strip() for x in val.split(r'\n')] )

if __name__ == 'main':
    print 'This class is for module use only'
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.