本文整理匯總了Python中rapuma.core.tools.Tools.tStamp方法的典型用法代碼示例。如果您正苦於以下問題:Python Tools.tStamp方法的具體用法?Python Tools.tStamp怎麽用?Python Tools.tStamp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類rapuma.core.tools.Tools
的用法示例。
在下文中一共展示了Tools.tStamp方法的6個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: Template
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [as 別名]
#.........這裏部分代碼省略.........
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 != '' :
projHome = os.path.join(targetDir, self.pid)
elif self.local.projHome :
projHome = os.path.join(self.local.projHome, self.pid)
# self.tools.dieNow()
# Test to see if the project already exists
if self.pid in self.projList :
self.tools.terminal('\nError: Project ID [' + self.pid + '] is already exists on this system. Use the remove command to remove it.')
self.tools.dieNow()
# Test for source template file
if not source :
source = os.path.join(self.local.userLibTemplate, self.pid + '.zip')
if not os.path.exists(source) :
self.tools.terminal('\nError: No template can be found for [' + self.pid + ']\n')
self.tools.dieNow()
# Unzip the template in place to start the new project
with zipfile.ZipFile(source, 'r') as myzip :
myzip.extractall(projHome)
# Peek into the project
pc = ConfigObj(os.path.join(projHome, 'Config', 'project.conf'), encoding='utf-8')
pc['ProjectInfo']['projectCreateDate'] = self.tools.tStamp()
pc['ProjectInfo']['projectIDCode'] = self.pid
pc.filename = os.path.join(projHome, 'Config', 'project.conf')
pc.write()
# Get the media type from the newly placed project for registration
projectMediaIDCode = pc['ProjectInfo']['projectMediaIDCode']
# Reset the local settings
self.local = ProjLocal(self.pid)
# Create any folders that might be needed
for fld in self.local.projFolders :
folder = os.path.join(self.local.projHome, fld)
if not os.path.exists(folder) :
os.makedirs(folder)
# Report what happened
self.tools.terminal('A new project [' + self.pid + '] has been created based on the [' + self.tools.fName(source) + '] template.')
示例2: UserConfig
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [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')
示例3: Config
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [as 別名]
#.........這裏部分代碼省略.........
def getIllustrationConfig (self) :
'''Load/return the illustration configuation object.'''
self.illustrationConfig = self.tools.loadConfig(self.local.illustrationConfFile, self.local.illustrationConfXmlFile)
def getFontConfig (self) :
'''Load/return the font configuation object.'''
self.fontConfig = self.tools.loadConfig(self.local.fontConfFile, self.local.fontConfXmlFile)
def getMacroConfig (self) :
'''Load/return the macro configuration object.'''
self.macroConfig = self.tools.loadConfig(self.local.macroConfFile, self.local.macroConfXmlFile)
###############################################################################
############################ Manager Level Functions ##########################
###############################################################################
####################### Error Code Block Series = 1000 ########################
###############################################################################
def makeNewprojectConf (self, local, pid, cVersion, pmid='book') :
'''Create a new project configuration file for a new project.'''
self.projectConfig = ConfigObj(self.tools.getXMLSettings(os.path.join(local.rapumaConfigFolder, pmid + '.xml')), encoding='utf-8')
# Insert intitial project settings
self.projectConfig['ProjectInfo']['projectMediaIDCode'] = pmid
self.projectConfig['ProjectInfo']['creatorID'] = self.userConfig['System']['userID']
self.projectConfig['ProjectInfo']['projectCreatorVersion'] = cVersion
self.projectConfig['ProjectInfo']['projectCreateDate'] = self.tools.tStamp()
self.projectConfig['ProjectInfo']['projectIDCode'] = pid
self.projectConfig['Backup']['ownerID'] = self.userConfig['System']['userID']
self.projectConfig['Groups'] = {}
# Even though there was no push, we need a time stamp to avoid confusion
self.projectConfig['Backup']['lastCloudPush'] = self.tools.fullFileTimeStamp()
self.projectConfig.filename = local.projectConfFile
self.projectConfig.write()
###############################################################################
######################## Basic Config Handling Functions ######################
###############################################################################
####################### Error Code Block Series = 2000 ########################
###############################################################################
def processSinglePlaceholder (self, ph, value) :
'''Once we are sure we have a single placeholder (noting embedded) this
will process it and replace it with the correct value.'''
holderType = ph.split(':')[0]
try :
holderKey = ph.split(':')[1]
except :
holderKey = ''
if self.hasPlaceHolder(value):
value = self.processNestedPlaceholders(value, '')
result = ph # If nothing matches below, default to returning placeholder unchanged
if holderType == 'val' :
result = value
示例4: ProjBackground
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [as 別名]
#.........這裏部分代碼省略.........
figure out what the background is to be composed of and create
a master background page. Using force will cause it to be remade.'''
# Do a quick check if the background needs to be remade
# The background normally is not remade if one already exists.
# If one is there, it can be remade if regenerate is set to
# to True. Obviously, if one is not there, it will be made.
if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['regenerateBackground']) :
self.createBackground()
else :
# If there isn't one, make it
if not os.path.exists(self.local.backgroundFile) :
self.createBackground()
# Merge target with the project's background file in the Illustraton folder
self.log.writeToLog(self.errorCodes['1300'])
# Create a special name for the file with the background
# Then merge and save it
viewFile = self.tools.alterFileName(target, 'view')
shutil.copy(self.tools.mergePdfFilesPdftk(self.centerOnPrintPage(target), self.local.backgroundFile), viewFile)
# Not returning a file name would mean it failed
if os.path.exists(viewFile) :
return viewFile
def addDocInfo (self, target) :
'''Add (merge) document information to the rendered target doc.'''
# Initialize the process
docInfoText = self.layoutConfig['DocumentFeatures']['docInfoText']
timestamp = self.tools.tStamp()
if self.gid :
headerLine = self.pid + ' / ' + self.gid + ' / ' + timestamp
else :
headerLine = self.pid + ' / ' + timestamp
svgFile = tempfile.NamedTemporaryFile().name
## RENDERED PAGE DIMENSIONS (body)
# This can be determined with the pyPdf element
# "pdf.getPage(0).mediaBox", which returns a
# RectangleObject([0, 0, Width, Height]). The
# width and height are in points. Hopefully we will
# always be safe by measuring the gidPdfFile size.
#pdf = PdfFileReader(open(self.local.gidPdfFile,'rb'))
#var2 = pdf.getPage(0).mediaBox
#trimWidth = float(var2.getWidth())
#trimHeight = float(var2.getHeight())
trimWidth = float(self.layoutConfig['PageLayout']['pageWidth'])
trimHeight = float(self.layoutConfig['PageLayout']['pageHeight'])
# Printer page size
pps = self.printerPageSize()
ppsWidth = pps[0]
ppsHeight = pps[1]
ppsCenter = ppsWidth/2
# Write out SVG document text
with codecs.open(svgFile, 'wb') as fbackgr : # open file for writing
fbackgr.write( '''<svg xmlns="http://www.w3.org/2000/svg"
version="1.1" width = "''' + str(ppsWidth) + '''" height = "''' + str(ppsHeight) + '''">
<g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(20) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + headerLine + '''</text></g>
<g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(ppsHeight-30) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + self.tools.fName(target) + '''</text></g>
<g><text x = "''' + str(ppsCenter) + '''" y = "''' + str(ppsHeight-20) + '''" style="font-family:DejaVu Sans;font-style:regular;font-size:8;text-anchor:middle;fill:#000000;fill-opacity:1">''' + docInfoText + '''</text></g>
</svg>''')
示例5: ProjLog
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [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()
#.........這裏部分代碼省略.........
示例6: UserConfig
# 需要導入模塊: from rapuma.core.tools import Tools [as 別名]
# 或者: from rapuma.core.tools.Tools import tStamp [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"])
#.........這裏部分代碼省略.........