当前位置: 首页>>代码示例>>Python>>正文


Python Tools.terminal方法代码示例

本文整理汇总了Python中rapuma.core.tools.Tools.terminal方法的典型用法代码示例。如果您正苦于以下问题:Python Tools.terminal方法的具体用法?Python Tools.terminal怎么用?Python Tools.terminal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rapuma.core.tools.Tools的用法示例。


在下文中一共展示了Tools.terminal方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Group

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class Group (object) :

    # Shared values
    xmlConfFile     = 'group.xml'

    def __init__(self, project, cfg, parent = None) :
        '''Initialize this class.'''

        self.project = project
        self.cfg = cfg
        self.parent = parent or project
        self.managers = {}
        self.tools = Tools()


    def render(self) :
        '''Render a group.'''

        self.tools.terminal("Warning: Calling dummy rendering in the group class.")
开发者ID:jstnlth,项目名称:rapuma,代码行数:21,代码来源:group.py

示例2: Template

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class Template (object) :

    def __init__(self, pid) :
        '''Intitate the whole class and create the object.'''

        self.pid            = pid
        self.tools          = Tools()
        self.user           = UserConfig()
        self.userConfig     = self.user.userConfig
        self.local          = ProjLocal(pid)
        self.log            = ProjLog(pid)
        self.projData       = ProjData(pid)


    def projectToTemplate (self, tid = None) :
        '''Preserve critical project information in a template. The pid is the project
        that the template will be bassed from. The template will go in the template lib.'''

        # Set needed vals
        if not tid :
            tid             = self.pid
        tempDir             = os.path.join(tempfile.mkdtemp(), tid)
        target              = os.path.join(self.local.userLibTemplate, tid + '.zip')

        # Make a temp copy of the project that we can manipulate
        shutil.copytree(self.local.projHome, tempDir)

        # Now make the config files generic for use with any project
        tc = ConfigObj(os.path.join(tempDir, 'Config', 'project.conf'), encoding='utf-8')
        tc['ProjectInfo']['projectTitle']               = ''
        tc['ProjectInfo']['projectIDCode']              = ''
        tc['ProjectInfo']['projectCreateDate']          = ''
        tc['ProjectInfo']['projectCreateDate']          = ''
        # Remove unnecessary folders
        needNot = ['Component', 'Deliverable', 'Illustration']
        for f in needNot :
            fld = os.path.join(tempDir, f)
            if os.path.exists(fld) :
                shutil.rmtree(fld)
        # Remove unnecessary config files
        needNot = ['adjustment', 'illustration']
        for f in needNot :
            fl = os.path.join(tempDir, 'Config', f + '.conf')
            if os.path.exists(fl) :
                os.remove(fl)
        # Remove unnecessary project config stuff
        needNot = ['Groups', 'Backup']
        for s in needNot :
            if tc.has_key(s) :
                del tc[s]
        # Write out the new template project config file
        tc.filename = os.path.join(tempDir, 'Config', 'project.conf')
        tc.write()

        # Kill the log file
        os.remove(os.path.join(tempDir, 'rapuma.log'))

        # Exclude files
        excludeFiles = self.projData.makeExcludeFileList(source)

        # Zip it up using the above params
        root_len = len(tempDir)
        with zipfile.ZipFile(target, 'w', compression=zipfile.ZIP_DEFLATED) as myzip :
            sys.stdout.write('Creating template')
            sys.stdout.flush()
            for root, dirs, files in os.walk(tempDir):
                # Chop off the part of the path we do not need to store
                zip_root = os.path.abspath(root)[root_len:]
                for f in files:
                    if f[-1] == '~' :
                        continue
                    elif f in excludeFiles :
                        continue
                    elif f.rfind('.') != -1 :
                        fullpath = os.path.join(root, f)
                        zip_name = os.path.join(zip_root, f)
                        sys.stdout.write('.')
                        sys.stdout.flush()
                        myzip.write(fullpath, zip_name, zipfile.ZIP_DEFLATED)

            # Add space for next message
            sys.stdout.write('\n')

        # Remove the temp project dir we made
        self.tools.terminal('\nCompleted creating template: ' + target + '\n')


    def templateToProject (self, targetDir = None, source = None) :
        '''Create a new project based on the provided template ID. If a path to
        the template is not provided it will look in the users template lib. A PID
        must be provided. That is checked with the system. If the same PID is
        found in the system, it must be removed before reruning this function. If
        a non-default location is needed, a target path must be provided.'''

#        import pdb; pdb.set_trace()

        # Set a default target path
        projHome = os.path.join(self.local.projParentDefaultFolder, self.pid)
        # See if we can build a better target path
        if targetDir != '' :
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_data.py

示例3: ProjData

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]

#.........这里部分代码省略.........
                else :
                    # Get rid of edited backup files
                    if fileName[-1] == '~' :
                        excludeFiles.append(os.path.join(root, fileName))
                        continue
                    ext = os.path.splitext(fileName)[1][1:]
                    if ext in excludeTypes :
                        # A special indicator for file we want to keep
                        if fileName.find('-ext.') > 0 :
                            continue

        return excludeFiles

# FIXME: Should archiveProject() use self.pid instead of explicitly passing in a pid?
    def archiveProject (self, pid, path = None) :
        '''Archive a project. Send the compressed archive file to the user-specified
        archive folder. If none is specified, put the archive in cwd. If a valid
        path is specified, send it to that location. Like backup, this too will
        overwrite any existing file of the same name. The difference is that this
        will also disable the project so it cannot be accesses by Rapuma. When a
        project is archived, all work should cease on the project.'''

        # Make a private project object just for archiving
        aProject = Project(pid, self.gid)
        # Set some paths and file names
        archName = aProject.projectIDCode + '.rapuma'
        userArchives = self.userConfig['Resources']['archive']
        archTarget = ''
        if path :
            path = self.tools.resolvePath(path)
            if os.path.isdir(path) :
                archTarget = os.path.join(path, archName)
            else :
                self.tools.terminal('\nError: The path given is not valid: [' + path + ']\n')
                self.tools.dieNow()
        elif os.path.isdir(userArchives) :
            archTarget = os.path.join(userArchives, archName)
        elif os.path.isdir(os.path.dirname(aProject.local.projHome)) :
            # Default to the dir just above the project
            archTarget = os.path.dirname(aProject.local.projHome)
        else :
            self.tools.terminal('\nError: Cannot resolve a path to create the archive file!\n')
            self.tools.dieNow()

        # Get a list of files we don't want
        excludeFiles = self.makeExcludeFileList(source)

        self.zipUpProject(archTarget, excludeFiles)

        # Rename the source dir to indicate it was archived
        bakArchProjDir = aProject.local.projHome + '(archived)'
        if os.path.isdir(bakArchProjDir) :
            self.tools.terminal('\nError: Cannot complete archival process!\n')
            self.tools.terminal('\nAnother archived version of this project exsits with the folder name of: ' + self.tools.fName(bakArchProjDir) + '\n')
            self.tools.terminal('\nPlease remove or rename it and then repete the process.\n')
            self.tools.dieNow()
        else :
            os.rename(aProject.local.projHome, bakArchProjDir)

        # Finish here
        self.tools.terminal('Archive for [' + pid + '] created and saved to: ' + archTarget + '\n')


    def zipUpProject (self, target, excludeFiles = None) :
        '''Zip up a project and deposit it to target location. Be sure to strip
        out all all auto-created, user-specific files that could mess up a
开发者ID:jstnlth,项目名称:rapuma,代码行数:70,代码来源:proj_data.py

示例4: UserConfig

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class UserConfig (object) :

    def __init__(self) :
        '''Intitate the whole class and create the object.'''

#        import pdb; pdb.set_trace()

        self.rapumaHome         = os.environ.get('RAPUMA_BASE')
        self.defaultUserHome    = os.environ.get('RAPUMA_USER')
        self.userConfFileName   = 'rapuma.conf'
        self.tools              = Tools()

        # Point to the right user config either server or desktop
        # The RAPUMA_USER setting should have the right path from
        # the mother script (rapuma)
        self.userConfFile       = os.path.join(self.defaultUserHome, self.userConfFileName)

        # Check to see if the file is there, then read it in and break it into
        # sections. If it fails, scream really loud!
        rapumaXMLDefaults = os.path.join(self.rapumaHome, 'config', 'rapuma.xml')
        if os.path.exists(rapumaXMLDefaults) :
            self.tools.sysXmlConfig = self.tools.xml_to_section(rapumaXMLDefaults)
        else :
            raise IOError, "Can't open " + rapumaXMLDefaults

        # Now make the users local rapuma.conf file if it isn't there
        if not os.path.isfile(self.userConfFile) :
            self.initUserHome()

        # Load the system.conf file into an object
        self.userConfig = ConfigObj(self.userConfFile, encoding='utf-8')

        # Log messages for this module
        self.errorCodes     = {
            '0000' : ['MSG', 'Placeholder message'],
        }

###############################################################################
############################ User Config Functions ############################
###############################################################################

    def initUserHome (self) :
        '''Initialize a user config file on a new install or system re-init.'''

        # Create home folders
        if not os.path.isdir(self.defaultUserHome) :
            os.mkdir(self.defaultUserHome)

        # Make the default global rapuma.conf for custom environment settings
        if not os.path.isfile(self.userConfFile) :
            self.userConfig = ConfigObj(self.tools.sysXmlConfig.dict(), encoding='utf-8')
            self.userConfig.filename = self.userConfFile
            self.userConfig['System']['initDate'] = self.tools.tStamp()
            self.userConfig.write()


    def setSystemSettings (self, section, key, value) :
        '''Function to make system settings.'''

        oldValue = self.userConfig[section][key]
        if oldValue != value :
            self.userConfig[section][key] = value
            # Write out the results
            self.userConfig.write()
            self.tools.terminal('\nRapuma user name setting changed from [' + oldValue + '] to [' + value + '].\n\n')
        else :
            self.tools.terminal('\nSame value given, nothing to changed.\n\n')
开发者ID:sillsdev,项目名称:rapuma,代码行数:69,代码来源:user_config.py

示例5: ProjCommander

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class ProjCommander (object) :

    def __init__(self, pid) :
        '''Intitate the whole class and create the object.'''

        self.pid                    = pid
        self.tools                  = Tools()
        self.user                   = UserConfig()
        self.userConfig             = self.user.userConfig
        self.projHome               = os.path.join(os.environ['RAPUMA_PROJECTS'], self.pid)
        self.local                  = ProjLocal(self.pid)
        self.proj_config            = Config(pid)
        self.proj_config.getProjectConfig()
        self.projectConfig          = self.proj_config.projectConfig
        self.projectMediaIDCode     = self.projectConfig['ProjectInfo']['projectMediaIDCode']

        # Log messages for this module
        self.errorCodes     = {
            '0000' : ['MSG', 'Placeholder message'],
        }


###############################################################################
########################## Command Creation Functions #########################
###############################################################################

    def removeScripts (self) :
        '''Remove any unnecessary group control scripts from the project.'''

        self.tools.dieNow('removeScripts() not implemented yet.')


    def updateScripts (self) :
        '''Update all the helper command scripts in a project.'''

        self.makeStaticScripts()
        self.makeGrpScripts()


    def makeGrpScripts (self) :
        '''Create scripts that process specific group components.'''

        if not os.path.isdir(self.local.projHelpScriptFolder) :
            os.mkdir(self.local.projHelpScriptFolder)

        # Output the scripts (If this is a new project we need to pass)
        if self.projectConfig.has_key('Groups') :
            for gid in self.projectConfig['Groups'].keys() :
                allScripts = self.getGrpScripInfo(gid)
                for key in allScripts.keys() :
                    fullFile = os.path.join(self.local.projHelpScriptFolder, key) + gid
                    with codecs.open(fullFile, "w", encoding='utf_8') as writeObject :
                        writeObject.write(self.makeScriptHeader(allScripts[key][0], allScripts[key][1]))
                        # Strip out extra spaces from command
                        cmd = re.sub(ur'\s+', ur' ', allScripts[key][1])
                        writeObject.write(cmd + '\n\n')

                    # Make the script executable
                    self.tools.makeExecutable(fullFile)
            
            self.tools.terminal('\nCompleted creating/recreating group helper scripts.\n')
        else :
            pass


    def makeStaticScripts (self) :
        '''Create helper scripts for a project to help with repetitive tasks.
        If any scripts are present with the same name they will be overwritten.
        Note: This is only for temporary use due to the lack of an interface at
        this time (20130306140636). It assumes the cType is usfm which, at some point
        may not be the case.'''

        if not os.path.isdir(self.local.projHelpScriptFolder) :
            os.mkdir(self.local.projHelpScriptFolder)

        # Output the scripts
        allScripts = self.getStaticScripInfo()
        for key in allScripts.keys() :
            fullFile = os.path.join(self.local.projHelpScriptFolder, key)
            with codecs.open(fullFile, "w", encoding='utf_8') as writeObject :
                writeObject.write(self.makeScriptHeader(allScripts[key][0], allScripts[key][1]))
                writeObject.write(allScripts[key][1] + '\n\n')

            # Make the script executable
            self.tools.makeExecutable(fullFile)

        self.tools.terminal('\nCompleted creating/recreating static helper scripts.\n')


    def makeScriptHeader (self, desc, cmd) :
        '''Make a helper script header.'''

        return '#!/bin/sh\n\n# Description: ' + desc + '\n\necho \necho Rapuma helper script: ' + desc + '\n\necho \necho command: ' + self.echoClean(cmd) + '\n\n'


    def echoClean (self, cmdStr) :
        '''Clean up a string for an echo statement in a shell script.'''

        clean = re.sub(ur'\;', ur'\\;', cmdStr)
        clean = re.sub(ur'\s+', ur' ', clean)
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:proj_commander.py

示例6: ProjBackground

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]

#.........这里部分代码省略.........


# Depricated
    #def makeBgFileName (self, orgName) :
        #'''Alter the file name to reflect the fact it has a background
        #added to it. This assumes the file only has a single extention.
        #If that's not the case we're hosed.'''

        #name    = orgName.split('.')[0]
        #ext     = orgName.split('.')[1]
        ## Just in case this is the second pass
        #name    = name.replace('-bg', '')
        #return name + '-bg.' + ext


    def centerOnPrintPage (self, contents) :
        '''Center a PDF file on the printerPageSize page. GhostScript
        is the only way to do this at this point.'''

#        import pdb; pdb.set_trace()

        tmpFile = tempfile.NamedTemporaryFile().name
        # Get the size of our printer page
        (ppsWidth, ppsHeight) = self.printerPageSize()
        (wo, ho) = self.getPageOffset()
        pageOffset = str(wo) + ' ' + str(ho)
        
        # Assemble the GhostScript command
        cmd = [ 'gs', 
                '-o', tmpFile, 
                '-sDEVICE=pdfwrite', 
                '-dQUIET', 
                '-dDEVICEWIDTHPOINTS=' + str(ppsWidth),
                '-dDEVICEHEIGHTPOINTS=' + str(ppsHeight),
                '-dFIXEDMEDIA', 
                '-c', 
                '<</PageOffset [' + str(pageOffset) + ']>>', 
                'setpagedevice', 
                '-f', 
                contents]

        if self.debugMode :
            self.tools.terminal('Debug Mode On: \centerOnPrintPage() command: ' + str(cmd))

        # Run the process
        try:
            subprocess.call(cmd) 
            # Return the name of the temp PDF
            return tmpFile
        except Exception as e :
            self.log.writeToLog(self.errorCodes['1280'], [str(cmd), str(e)])
        # Return the temp file name for further processing


    def printerPageSize (self) :
        '''Return the width and height of the printer page size in
        points. Only US Letter and A4 are supported. If not specified
        return the page trim size.'''
    
        printerPageSizeCode = self.layoutConfig['PageLayout']['printerPageSizeCode'].lower()
        ## STANDARD PRINTER PAGE SIZES
        # The output page (printer page) is what the typeset page will be placed on
        # with a watermark behind it. There are only two page sizes supported.
        # They are A4 and US Letter. We will determine the size by the ID code
        # found in the layout.conf file. However, in some cases, for example
        # during the layout process, the trim size is what is needed. If
        # one of the two supported pages sizes are not used, this will defult
        # to the trim size.
        if printerPageSizeCode == 'a4' :
            return float(595), float(842)
        elif printerPageSizeCode == 'letter' :
            return float(612), float(792)
        else :
            # Just default to the page trim size (assumed mm coming in) factor mmToPx = 72 / 25.4
            return float(int(self.layoutConfig['PageLayout']['pageWidth']) * self.mmToPx), float(int(self.layoutConfig['PageLayout']['pageHeight']) * self.mmToPx)

    
    def getPageOffset (self) :
        '''Return the amount of horizontal and vertical offset that will
        enable the page trim size to be centered on the printer page. If
        something other than A4 or Letter is being used, the offset returned
        will be zero as this only supports those two sizes. The offset is
        based on the starting point being the lower-left side corner
        of the page. '''
        
        # Get the printer page size
        printerPageSizeCode = self.layoutConfig['PageLayout']['printerPageSizeCode'].lower()
        # Get the page trim size (assuming mm input)factor mmToPx = 72 / 25.4
        trimWidth = int(self.layoutConfig['PageLayout']['pageWidth']) * self.mmToPx
        trimHeight = int(self.layoutConfig['PageLayout']['pageHeight']) * self.mmToPx

        # The trim size of the content page can never be bigger than
        # the printer page size. If so, the offset is 0
        if printerPageSizeCode == 'a4' or printerPageSizeCode == 'letter' :
            (bw, bh) = self.printerPageSize()
            wo = float((bw/2)-(trimWidth/2))
            ho = float((bh/2)-(trimHeight/2))
            return wo, ho
        else :
            return 0, 0
开发者ID:sillsdev,项目名称:rapuma,代码行数:104,代码来源:proj_background.py

示例7: Tools

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
tools = Tools()

source = sys.argv[1]
tempFile = source + '.tmp'
bakFile = source + '.bak'
# Make backup and temp file
shutil.copy(source, bakFile)

# Read in the source file
contents = codecs.open(source, "rt", encoding="utf_8_sig").read()

# Do stuff here

# Please delete this warning message when you start modifying this script.
tools.terminal('\nThe group preprocess script has not been modified yet. It is in its default form. Nothing has been done to the component data.\n(This anoying little message can be found in a file in your project Script folder.)\n')

# Examples:
# Change cross reference into footnotes
#contents = re.sub(ur'\\x(\s.+?)\\xo(\s\d+:\d+)(.+?)\\x\*', ur'\\f\1\\fr\2 \\ft\3\\f*', contents)

# Insert horizontal rule after intro section
#contents = re.sub(ur'(\\c\s1\r\n)', ur'\skipline\n\hrule\r\n\1', contents)

# Insert a chapter label marker with zwsp to center the chapter number
#contents = re.sub(ur'(\\c\s1\r\n)', ur'\cl \u200b\r\n\1', contents)

# Write out a temp file so we can do some checks
codecs.open(tempFile, "wt", encoding="utf_8_sig").write(contents)

# Finish by copying the tempFile to the source
开发者ID:jstnlth,项目名称:rapuma,代码行数:32,代码来源:textPreprocess.py

示例8: ProjLog

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class ProjLog (object) :

    def __init__(self, pid) :
        '''Do the primary initialization for this manager.'''

        self.tools              = Tools()
        self.pid                = pid
        self.rapumaHome         = os.environ.get('RAPUMA_BASE')
        self.userHome           = os.environ.get('RAPUMA_USER')
        self.user               = UserConfig()
        self.userConfig         = self.user.userConfig
        self.local              = ProjLocal(pid)


###############################################################################
############################### Logging Functions #############################
###############################################################################

# These have to do with keeping a running project log file.  Everything done is
# recorded in the log file and that file is trimmed to a length that is
# specified in the system settings.  Everything is channeled to the log file but
# depending on what has happened, they are classed in three levels:
#   1) [MSG] - Common event going to log and terminal
#   2) [WRN] - Warning event going to log and terminal if debugging is turned on
#   3) [ERR] - Error event going to the log and terminal and kills the process
#   4) [LOG] - Messages that go only to the log file to help with debugging
# FIXME: Following not implemented yet
#   5) [TOD] - To do list. Output to a file that helps guide the user.


    def writeToLog (self, errCode, args=None, location=None) :
        '''Send an event to one of the log files or the terminal if specified.
        Everything gets written to a log.  Where a message gets written to
        depends on what type code it is.  The type code is in with the error
        code data.  There are five type codes:
            MSG = General messages go to both the terminal and log file
            LOG = Messages that go only to the log file
            WRN = Warnings that go to the terminal and log file
            ERR = Errors that go to both the terminal and log file
            TOD = Messages that will go to a special todo file to guide the user
        The errCode points to a specific message that will be sent to a log
        file. The args parameter can contain extra information like file names
        to help the user better figure out what happened.'''

        # Get the message from the errorCode list the module sent
        if type(errCode) == list :
            if location :
                msg = errCode[1] + ' : (' + location + ')'
            else :
                msg = errCode[1]
            code = errCode[0]
        else :
            self.tools.terminal('\nThe code: [' + errCode + '] is not recognized by the Rapuma system.')
            return

        # If args were given, do s/r on them and add 
        # args info that needs to be added to msg.
        # Look for a <<#>> pattern replace it with
        # the corresponding position in the args list.
        if args :
            for count, arg in enumerate(args) :
                msg = msg.replace('<<' + str(count+1) + '>>', arg)

        # Write out everything but LOG messages to the terminal
        if code != 'LOG' and code != 'TOD' :
            self.tools.terminal('\n' + code + ' - ' + msg)

        # Test to see if this is a live project by seeing if the project conf is
        # there.  If it is, we can write out log files.  Otherwise, why bother?
        if self.local.projectConfFile and os.path.exists(self.local.projectConfFile) :

            # Build the event line
            eventLine = '\"' + self.tools.tStamp() + '\", \"' + code + '\", \"' + msg + '\"'

            # Do we need a log file made?
            try :
                if not os.path.isfile(self.local.projLogFile) or os.path.getsize(self.local.projLogFile) == 0 :
                    writeObject = codecs.open(self.local.projLogFile, "w", encoding='utf_8')
                    writeObject.write('Rapuma event log file created: ' + self.tools.tStamp() + '\n')
                    writeObject.close()

                # Now log the event to the top of the log file using preAppend().
                self.preAppend(eventLine, self.local.projLogFile)

                # FIXME: Add the TOD list output here, also, output any TODs 
                # to the error log as well as these are bad errors.

                # Write errors and warnings to the error log file
                if code == 'WRN' and self.userConfig['System']['debugging'] == 'True':
                    self.writeToErrorLog(self.local.projErrorLogFile, eventLine)

                if code == 'ERR' :
                    self.writeToErrorLog(self.local.projErrorLogFile, eventLine)

            except Exception as e :
                # If we don't succeed, we should probably quite here
                self.tools.terminal("Failed to write message to log file: " + msg)
                self.tools.terminal('Internal error: [' + str(e) + ']')
                self.tools.dieNow()
            
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_log.py

示例9: UserConfig

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import terminal [as 别名]
class UserConfig(object):
    def __init__(self):
        """Intitate the whole class and create the object."""

        self.rapumaHome = os.environ.get("RAPUMA_BASE")
        self.defaultUserHome = os.environ.get("RAPUMA_USER")
        self.userConfFileName = "rapuma.conf"
        self.tools = Tools()

        # Point to the right user config
        # Look for a web installation first, if not go to default
        # Note that a slash is put before var as it is off of root
        # That kind of stops this from being cross-platform
        rapumaWebConfig = os.path.join("/var", "lib", "rapuma", "config", self.userConfFileName)
        defaultConfig = os.path.join(self.defaultUserHome, self.userConfFileName)
        if os.path.exists(rapumaWebConfig):
            self.userConfFile = rapumaWebConfig
        else:
            self.userConfFile = defaultConfig

        # Check to see if the file is there, then read it in and break it into
        # sections. If it fails, scream really loud!
        rapumaXMLDefaults = os.path.join(self.rapumaHome, "config", "rapuma.xml")
        if os.path.exists(rapumaXMLDefaults):
            self.tools.sysXmlConfig = self.tools.xml_to_section(rapumaXMLDefaults)
        else:
            raise IOError, "Can't open " + rapumaXMLDefaults

        #        import pdb; pdb.set_trace()

        # Now make the users local rapuma.conf file if it isn't there
        if not os.path.exists(self.userConfFile):
            self.initUserHome()

        # Load the Rapuma conf file into an object
        self.userConfig = ConfigObj(self.userConfFile, encoding="utf-8")

        # Initialize the user's home folders, like resources, etc
        self.makeHomeFolders()

        # Log messages for this module
        self.errorCodes = {"0000": ["MSG", "Placeholder message"]}

    ###############################################################################
    ############################ User Config Functions ############################
    ###############################################################################

    def initUserHome(self):
        """Initialize a user config file on a new install or system re-init."""

        # Create home folders
        if not os.path.isdir(self.defaultUserHome):
            os.mkdir(self.defaultUserHome)

        # Make the default global rapuma.conf for custom environment settings
        if not os.path.isfile(self.userConfFile):
            self.userConfig = ConfigObj(self.tools.sysXmlConfig.dict(), encoding="utf-8")
            self.userConfig.filename = self.userConfFile
            self.userConfig["System"]["initDate"] = self.tools.tStamp()
            self.userConfig.write()

    def setSystemSettings(self, section, key, value):
        """Function to make system settings."""

        oldValue = self.userConfig[section][key]
        if oldValue != value:
            self.userConfig[section][key] = value
            # Write out the results
            self.userConfig.write()
            self.tools.terminal("\nRapuma user name setting changed from [" + oldValue + "] to [" + value + "].\n\n")
        else:
            self.tools.terminal("\nSame value given, nothing to changed.\n\n")

    def makeHomeFolders(self):
        """Setup the default Rapuma resource folders."""

        #        import pdb; pdb.set_trace()

        # We do not write out unless this flag is set
        confWriteFlag = False

        # Setup Resources section if needed
        if not self.userConfig.has_key("Resources"):
            self.tools.buildConfSection(self.userConfig, "Resources")

        # Get the user config project folder location (or set a default)
        if not self.userConfig["Resources"].has_key("projects") or not self.userConfig["Resources"]["projects"]:
            projects = os.path.join(os.environ.get("HOME"), "Publishing")
            if not os.path.exists(projects):
                os.makedirs(projects)
            self.userConfig["Resources"]["projects"] = projects
            confWriteFlag = True
        elif not os.path.exists(self.tools.resolvePath(self.userConfig["Resources"]["projects"])):
            sys.exit(
                "\nERROR: Invalid projects folder path: "
                + self.userConfig["Resources"]["projects"]
                + "\n\nProcess halted.\n"
            )
        else:
            projects = self.tools.resolvePath(self.userConfig["Resources"]["projects"])
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:user_config.py


注:本文中的rapuma.core.tools.Tools.terminal方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。