本文整理汇总了Python中pyaid.debug.Logger.Logger.write方法的典型用法代码示例。如果您正苦于以下问题:Python Logger.write方法的具体用法?Python Logger.write怎么用?Python Logger.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyaid.debug.Logger.Logger
的用法示例。
在下文中一共展示了Logger.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: IncludeCompressor
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class IncludeCompressor(object):
#===================================================================================================
# C L A S S
_REMOVE_COMMENT_RE = re.compile('/\*.+\*/', re.DOTALL)
_REMOVE_COMMENT_LINE_RE = re.compile('(^|\n)[\s\t]*//.+(\n|$)')
JS_TYPE = 'js'
CSS_TYPE = 'css'
#___________________________________________________________________________________________________ __init__
def __init__(self, compileCoffee =False):
self._log = Logger('IncludeCompressor')
self._compileCoffee = compileCoffee
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ compress
def compress(self, rootPath):
if not self._fileExists(rootPath):
return False
elif os.path.isfile(rootPath):
return self.compressFile(rootPath)
else:
return self.compressPath(rootPath)
#___________________________________________________________________________________________________ compressFile
def compressFile(self, rootPath, directory =None):
if not self._fileExists(rootPath):
return False
if self._compileCoffee:
try:
from pyaid.web.coffeescript.CoffeescriptBuilder import CoffeescriptBuilder
CoffeescriptBuilder.compileAllOnPath(rootPath, os.path.dirname(rootPath), True)
self._log.write('Coffeescript compiled.')
except Exception, err:
self._log.writeError('Failed to compile coffeescript file.', err)
return False
return self._compressFile(rootPath, directory)
示例2: DataFormatConverter
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class DataFormatConverter(object):
"""A class for converting between various data interchange formats, e.g. XML and JSON."""
#===================================================================================================
# C L A S S
#___________________________________________________________________________________________________ __init__
def __init__(self):
"""Creates a new instance of ClassTemplate."""
self._type = None
self._src = None
self._log = Logger('DataFormatConverter')
self._path = None
#===================================================================================================
# G E T / S E T
#___________________________________________________________________________________________________ GS: propertyName
@property
def source(self):
return self._src
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ load
def load(self, path, fileType):
if not os.path.exists(path):
self._log.write('ERROR: Path does not exist [%s]. Unable to load.' % path)
return False
try:
fh = codecs.open(path, 'r', 'utf-8')
res = fh.read()
fh.close()
enc = res.encode('utf-8')
self.loads(enc, fileType)
except Exception, err:
self._log.writeError('Failed to load source file [%s].' % path, err)
return False
self._path = path
return True
示例3: SocketHandler
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class SocketHandler(SocketServer.StreamRequestHandler):
"""A class for..."""
#===================================================================================================
# C L A S S
SERVICE_UID = 'test'
VERBOSE = False
WORK_PATH = '/var/lib/'
RUN_PATH = '/var/run/'
LOG_PATH = '/var/log/'
#___________________________________________________________________________________________________ __init__
def __init__(self, request, client_address, server):
self._log = Logger(self)
self._log.write('Socket handler created')
SocketServer.StreamRequestHandler.__init__(self, request, client_address, server)
#===================================================================================================
# G E T / S E T
#___________________________________________________________________________________________________ GS: returnResponse
@property
def returnResponse(self):
return getattr(self.__class__, 'RETURN_RESPONSE', False)
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ handle
def handle(self):
try:
data = self.rfile.readline().strip()
self._log.write('HANDLE: ' + str(data))
try:
result = self._respondImpl(JSON.fromString(unquote(data)))
except Exception as err:
self._log.writeError('RESPOND FAILURE', err)
if self.returnResponse:
self.wfile.write(JSON.asString({'error':1}))
return
if self.returnResponse:
out = {'error':0}
if result:
out['payload'] = result
self.wfile.write(out)
except Exception as err:
self._log.write('HANDLE FAILURE', err)
return
#===================================================================================================
# P R O T E C T E D
#___________________________________________________________________________________________________ _respondImpl
def _respondImpl(self, data):
pass
示例4: TrackCsvImporter
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class TrackCsvImporter(object):
""" Imports track data from CSV formatted spreadsheets into the local Cadence database. """
#===============================================================================
# C L A S S
# Used to break trackway specifier into separate type and number entries
_TRACKWAY_PATTERN = re.compile('(?P<type>[^0-9\s\t]+)[\s\t]*(?P<number>[^\(\s\t]+)')
_UNDERPRINT_IGNORE_TRACKWAY_STR = ':UTW'
_OVERPRINT_IGNORE_TRACKWAY_STR = ':OTW'
#_______________________________________________________________________________
def __init__(self, path =None, logger =None):
"""Creates a new instance of TrackCsvImporter."""
self._path = path
self.created = []
self.modified = []
self.fingerprints = dict()
self.remainingTracks = dict()
self._logger = logger
if not logger:
self._logger = Logger(self, printOut=True)
#===============================================================================
# P U B L I C
#_______________________________________________________________________________
def read(self, session, analysisSession, path =None, compressed =False):
""" Reads from the spreadsheet located at the absolute path argument and adds each row
to the tracks in the database. """
if path is not None:
self._path = path
if self._path is None:
return False
model = Tracks_Track.MASTER
for existingTrack in session.query(model).all():
self.remainingTracks[existingTrack.uid] = existingTrack.fingerprint
try:
data = pd.read_csv(self._path)
except Exception as err:
self._writeError({
'message':'ERROR: Unable to read CSV file "%s"' % self._path,
'error':err })
return
if data is None:
self._writeError({
'message':'ERROR: Failed to create CSV reader for file "%s"' % self._path })
return
for index, row in data.iterrows():
# Skip any rows that don't start with the proper numeric index value, which
# includes the header row (if it exists) with the column names
try:
index = int(row[0])
except Exception:
continue
rowDict = dict()
for column in Reflection.getReflectionList(TrackCsvColumnEnum):
value = row[column.index]
if value and StringUtils.isStringType(value) and not StringUtils.isTextType(value):
# Try to decode the value into a unicode string using common codecs
for codec in ['utf8', 'MacRoman', 'utf16']:
try:
decodedValue = value.decode(codec)
if decodedValue:
value = decodedValue
break
except Exception:
continue
try:
# Check to see if the value is NaN, and if it is replace it with an empty
# string to be ignored during import
value = '' if np.isnan(value) else value
except Exception:
pass
if value != '' or value is None:
rowDict[column.name] = value
self.fromSpreadsheetEntry(rowDict, session)
for uid, fingerprint in DictUtils.iter(self.remainingTracks):
# Iterate through the list of remaining tracks, which are tracks not found by the
# importer. If the track is marked as custom (meaning it is not managed by the importer)
# it is ignored. Otherwise, the track is deleted from the database as a track that no
# longer exists.
track = Tracks_Track.MASTER.getByUid(uid, session)
if track.custom:
continue
#.........这里部分代码省略.........
示例5: PyGlassWindow
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
#.........这里部分代码省略.........
self._lastChildWidgetID = self._currentWidget.widgetID
self._currentWidget = widget
if self._centerWidget:
layout = self._centerWidget.layout()
if not layout:
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._centerWidget.setLayout(layout)
layout.addWidget(widget)
else:
self._contentWrappingWidget.layout().addWidget(widget)
self.setContentsMargins(0, 0, 0, 0)
self.refreshGui()
if args is None:
args = dict()
widget.activateWidgetDisplay(lastPeerWidgetID=self._lastChildWidgetID, **args)
return True
#___________________________________________________________________________________________________ loadWidgets
def loadWidgets(self, widgetIdents =None):
if not widgetIdents:
widgetIdents = self._widgetClasses.keys()
elif StringUtils.isStringType(widgetIdents):
widgetIdents = [widgetIdents]
for widgetID in widgetIdents:
if widgetID in self._widgets:
continue
if widgetID not in self._widgetClasses:
self._log.write(
'ERROR: Unrecognized widgetID "%s" in %s' % (str(widgetID), str(self)))
try:
widget = self._widgetClasses[widgetID](
parent=self._widgetParent, flags=self._widgetFlags, widgetID=widgetID)
self._widgets[widgetID] = widget
except Exception as err:
self._log.write('ERROR: Failed to load widget with id: "%s" ->' % widgetID)
raise
#___________________________________________________________________________________________________ refreshGui
def refreshGui(self):
self.qApplication.processEvents()
#___________________________________________________________________________________________________ exit
def exit(self):
self.qApplication.exit()
#___________________________________________________________________________________________________ initialize
def initialize(self, *args, **kwargs):
self._initializeImpl(*args, **kwargs)
#___________________________________________________________________________________________________ initializeComplete
def initializeComplete(self, preDisplay =None):
self.pyGlassApplication.closeSplashScreen()
result = False
if preDisplay:
preDisplay.show()
result = self.qApplication.exec_()
if result:
示例6: PyGlassWindow
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
#.........这里部分代码省略.........
self._currentWidget.deactivateWidgetDisplay(**doneArgs)
self._currentWidget.setParent(self._widgetParent)
self._currentWidget = widget
if self._centerWidget:
layout = self._centerWidget.layout()
if not layout:
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self._centerWidget.setLayout(layout)
layout.addWidget(widget)
else:
self.setCentralWidget(widget)
self.setContentsMargins(0, 0, 0, 0)
self.refreshGui()
if args is None:
args = dict()
widget.activateWidgetDisplay(**args)
return True
#___________________________________________________________________________________________________ loadWidgets
def loadWidgets(self, widgetIdents =None):
if not widgetIdents:
widgetIdents = self._widgetClasses.keys()
elif isinstance(widgetIdents, basestring):
widgetIdents = [widgetIdents]
for widgetID in widgetIdents:
if widgetID in self._widgets:
continue
if widgetID not in self._widgetClasses:
self._log.write(
'ERROR: Unrecognized widgetID "%s" in %s' % (str(widgetID), str(self)))
widget = self._widgetClasses[widgetID](
self._widgetParent, flags=self._widgetFlags, widgetID=widgetID)
self._widgets[widgetID] = widget
#___________________________________________________________________________________________________ refreshGui
def refreshGui(self):
self.qApplication.processEvents()
#___________________________________________________________________________________________________ exit
def exit(self):
self.qApplication.exit()
#___________________________________________________________________________________________________ initialize
def initialize(self, *args, **kwargs):
if AlembicUtils.hasAlembic:
self.pyGlassApplication.updateSplashScreen('Conforming internal data')
AlembicUtils.upgradeAppDatabases(self.appID)
self._initializeImpl(*args, **kwargs)
#___________________________________________________________________________________________________ initializeComplete
def initializeComplete(self, preDisplay =None):
self.pyGlassApplication.closeSplashScreen()
result = False
if preDisplay:
preDisplay.show()
result = self.qApplication.exec_()
if not result:
示例7: TrackLinkConnector
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class TrackLinkConnector(object):
"""A class for..."""
#===============================================================================
# C L A S S
_TRACK_NUMBER_RE = re.compile('(?P<prefix>[^0-9\-]*)(?P<number>-?[0-9]+)(?P<suffix>[^0-9]*)')
#_______________________________________________________________________________
def __init__(self, logger =None):
"""Creates a new instance of TrackLinkConnector."""
self.logger = logger
if not logger:
self.logger = Logger(self, printOut=True)
self.searchNext = True
self.searchPrev = True
self.overrideExisting = False
self.operatedTracks = []
self.modifiedTracks = []
self.trackLinkages = []
#===============================================================================
# P U B L I C
#_______________________________________________________________________________
def echoResult(self):
out = []
for item in self.trackLinkages:
out.append(item[0].name + ' -> ' + item[1].name)
return u'\n'.join(out)
#_______________________________________________________________________________
def runAll(self, session):
model = Tracks_Track.MASTER
return self.run(session.query(model).all(), session)
#_______________________________________________________________________________
def run(self, tracks, session):
"""Doc..."""
for track in tracks:
if track not in self.operatedTracks:
self._runTrack(track, session)
#===============================================================================
# P R O T E C T E D
#_______________________________________________________________________________
def _runTrack(self, source, session):
"""Doc..."""
model = source.__class__
trackSeries = session.query(model).filter(
model.site == source.site,
model.sector == source.sector,
model.level == source.level,
model.trackwayType == source.trackwayType,
model.trackwayNumber == source.trackwayNumber,
model.pes == source.pes,
model.left == source.left).order_by(model.number.asc()).all()
if not trackSeries:
return False
#-------------------------------------------------------------------------------------------
# TRACK ORDERING
# Tracks numbers are strings to support naming conventions like 10b or 12c, where the
# number is possibly followed by a non-numeric set of characters. To establish track
# ordering the sequence should be sorted primarily by the numeric sequence and
# secondarily by the suffix first numerically and then alphabetically respectively.
trackNumbers = dict()
for track in trackSeries:
result = self._TRACK_NUMBER_RE.search(track.number)
if not result or result.group('prefix'):
self.logger.write([
u'ERROR: Unable to parse track number: ' + StringUtils.toUnicode(track.number),
u'TRACK: ' + DictUtils.prettyPrint(track.toDict()) ])
continue
number = result.group('number')
suffix = result.group('suffix')
if number not in trackNumbers:
trackNumbers[number] = {'track':None, 'extras':{}, 'number':int(number)}
entry = trackNumbers[number]
if number == track.number and not suffix:
entry['track'] = track
elif not suffix:
self.logger.write([
u'ERROR: Invalid track number: ' + StringUtils.toUnicode(track.number),
u'TRACK: ' + DictUtils.prettyPrint(track.toDict()) ])
continue
else:
entry['extras'][suffix] = track
if track not in self.operatedTracks:
self.operatedTracks.append(track)
#.........这里部分代码省略.........
示例8: CadenceDrawing
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class CadenceDrawing(object):
""" A class for writing Scalable Vector Graphics (SVG) files, tailored to create overlays for
site maps. Each site map has a marker that indicates a reference point in Swiss Federal
coordinates. At least one such marker appears somewhere within each site map (in cases
where there were two, the more central was chosen). The maps are all oriented such that
the x axis is positve to the right (towards the east) and the y axis is positive down
(southward). For visualization in Cadence, a site map is projected onto the y=0 plane of a
3D scene such that the Federal Coordinate marker is placed at the origin in 3D, and the
scene's positive x axis increases to the left ('west') and the scene's positive z axis
increases to the 'north'. The correspondence between these two coordinate systems is
handled by public functions to be found in this class, based on information derived from an
instance of a Tracks_SiteMap (specifically the scale and the location of a federal
coordinates marker within the siteMap).
This class wraps (owns) an instance of an svgwrite.Drawing and handles the mapping from 3D
scene coordinates (x, z) to SVG coordinates (x, y). Scene coordinates are in real-world cm,
while the SVG coordinates used in the sitemaps is in (50:1 scaled) mm. That is, one mm in
the _drawing equals 5 cm, realworld. By default, a saved CadenceDrawing can be placed in an
Adobe Illustrator layer, then adjusted to be in registation with the sitemap.
CadenceDrawing is built upon the svgwrite.Drawing class, which provides the basic
functions to draw lines, rectangles, and other SVG objects. For further information on
svgwrite, consult: https://pythonhosted.org/svgwrite
A CadenceDrawing instance simplifies the functionality of svgwrite, encapsulating all the
handling of all SVG fragments through function calls to create lines, polyLines, rects,
circles, elipses, and text, plus transformable groups, with the resultant SVG file written
by the function save. A CadenceDrawing adopts the underlying svgwrite convention of using
kwargs to provide a Pythonic means to specify SVG attributes such as stroke, stroke_linecap,
stroke_width, and fill. CadenceDrawing is a wrapper adaptation of svgwrite. That is, a
CadenceDrawing encapsulates an instance of an svgwrite Drawing. Coordinate mapping allows
trackway data (coordinates and dimensions) to be scaled appropriately for inclusion into an
SVG-format tracksite file to be placed in a layer in Adobe illustrator). This scaling is
provided by the kwarg scene=True, wherein scene coordinates (in cm) are converted to scaled
mm. The following is an example in which all tracks for a given site are loaded and drawn:
tracks = siteMap.getAllTracks(session)
for track in tracks:
x = track.x
z = track.z
# Track dimensions are in fractional meters, so multiply by 100 to convert to cm.
r = 100*0.5*(track.width/2.0 + track.length/2.0)
drawing.circle((x, z), r, scene=True, fill='none', stroke='blue', stroke_width=1)
# compute this track's averge uncertainty in cm (also stored in fractional meters)
u = 100*(track.widthUncertainty + track.lengthUncertainty)/2.0
drawing.circle((x, z), u, scene=True, fill='red', stroke='red', stroke_width=1)
A more advanced usage uses groups that can be transformed (rotated, scaled, translated).
A group is created and given an ID that is then passed to drawing functions (which create
the shape), then the group is used (instantiated) at somePlace at a rotation of 45 degrees:
drawing.createGroup('g1')
drawing.rect((0, 0), width, height, groupId='g1')
...etc...
drawing.use('g1', somePlace, rotation=45)
The use of groups, while convenient, requires that all map coordinates be converted to px.
For more detail, see the use function and grid, which produces a 10 m grid. """
# ===============================================================================
# C L A S S
# _______________________________________________________________________________
def __init__(
self,
fileName,
siteMap,
labelTracks=True,
labelColor="black",
session=None,
showUncertainty=True,
showCenters=True,
**kwargs
):
""" Creates a new instance of CadenceDrawing. Calls to the public functions line(), rect(),
and others result in objects being added to the SVG canvas, with the file written by the
save() method to specified fileName. The second argument, the siteMap is provided as an
argument to establish the correspondence between the Maya scene and the site siteMap
coordinates. """
self._logger = kwargs.get("logger")
if not self._logger:
self._logger = Logger(self, printOut=True)
self.siteMapReady = siteMap.isReady
if not self.siteMapReady:
self._logger.write('[ERROR|CadenceDrawing]: Sitemap "%s-%s" not ready' % (siteMap.name, siteMap.level))
return
self.fileName = fileName
self.siteMap = siteMap
self.siteName = siteMap.name
self.siteLevel = siteMap.level
# Generally units can be specified in millimeters. In a few cases, however, (e.g.,
# PolyLine) the coordinates must be unqualified integers (as px). The site maps, however
# are in 'scaled mm'. Hence the need for a cnversion factor pxPerMm. Unfortunately, the
# conversion between px and mm is OS-dependent. The conversion from px to inches is 72 for
# Apple but 90 more generally).
#.........这里部分代码省略.........
示例9: CoffeescriptBuilder
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class CoffeescriptBuilder(object):
"""A class for..."""
CLASS_PATTERN = "^[\s\t]*class[\s\t]+(?P<class>[^\s\t\r\n]+)[\s\t]*"
MISSING_CLASS_PATTERN = "[\s\t\(\[\{\!]+(?=[A-Z])(?P<class>[A-Za-z0-9_]+)(?P<next>[^A-Za-z0-9_]+)"
_WARN_ID_MISSING_IMPORT = "MISSING-IMPORT"
_GLOBAL_CLASSES = [
"SFLOW",
"PAGE",
"FB",
"Math",
"JSON",
"String",
"ActiveXObject",
"Date",
"DOMParser",
"RegExp",
"Object",
"Number",
"Array",
"Function",
"XMLHttpRequest",
]
_results = None
_missing = None
# ===================================================================================================
# C L A S S
# ___________________________________________________________________________________________________ __init__
def __init__(
self,
targetPackageOrPath,
rootPath,
verbose=True,
debug=False,
trace=False,
force=False,
compress=False,
buildOnly=False,
):
"""Creates a new instance of CoffeescriptBuilder."""
self.buildOnly = buildOnly
self._imports = dict()
self._requires = dict()
self._includes = dict()
self._report = dict()
self._warnings = []
self._dependencyReport = dict()
self._verbose = verbose
self._log = Logger(self, printOut=True)
self._trace = trace
self._debug = debug
self._targets = []
self._force = force
self._compress = compress
self._rootPath = rootPath
if not isinstance(targetPackageOrPath, CoffeescriptDependency):
target = CoffeescriptDependency(targetPackageOrPath, rootPath, None)
else:
target = targetPackageOrPath
if target.exists:
self._targets.append(target)
else:
csFiles = CoffeescriptBuilder.getScriptsInPath(target.packagePath)
# Look for exec matches first
for f in csFiles:
testTarget = CoffeescriptDependency(f, rootPath, None)
if testTarget.isExec:
self._targets.append(testTarget)
# Look for lib matches second. Lib matches are tested as a second pass because
# constructing all exec files first potentially optimizes the import process for
# the libraries.
for f in csFiles:
testTarget = CoffeescriptDependency(f, rootPath, None)
if testTarget.isLib:
self._targets.append(testTarget)
if len(self._targets) == 0:
print("\n\n")
self._log.write("No targets exist for: %s. Compilation aborted." % targetPackageOrPath)
print("\n")
# ===================================================================================================
# G E T / S E T
# ___________________________________________________________________________________________________ GS: report
@property
def report(self):
return self._report
#.........这里部分代码省略.........
示例10: CoffeescriptBuilder
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class CoffeescriptBuilder(object):
"""A class for..."""
CLASS_PATTERN = '^[\s\t]*class[\s\t]+(?P<class>[^\s\t\r\n]+)[\s\t]*'
MISSING_CLASS_PATTERN = '[\s\t\(\[\{\!]+(?=[A-Z])(?P<class>[A-Za-z0-9_]+)(?P<next>[^A-Za-z0-9_]+)'
_WARN_ID_MISSING_IMPORT = 'MISSING-IMPORT'
_GLOBAL_CLASSES = [
'SFLOW', 'PAGE', 'FB', 'Math', 'JSON', 'String', 'ActiveXObject', 'Date', 'DOMParser',
'RegExp', 'Object', 'Number', 'Array', 'Function', 'XMLHttpRequest']
_results = None
_missing = None
#===================================================================================================
# C L A S S
#___________________________________________________________________________________________________ __init__
def __init__(
self, targetPackageOrPath, rootPath, verbose =True, debug =False, trace = False,
force =False, compress =False, buildOnly =False
):
"""Creates a new instance of CoffeescriptBuilder."""
self.buildOnly = buildOnly
self._imports = dict()
self._requires = dict()
self._includes = dict()
self._report = dict()
self._warnings = []
self._dependencyReport = dict()
self._verbose = verbose
self._log = Logger(self, printOut=True)
self._trace = trace
self._debug = debug
self._targets = []
self._force = force
self._compress = compress
self._rootPath = rootPath
if not isinstance(targetPackageOrPath, CoffeescriptDependency):
target = CoffeescriptDependency(targetPackageOrPath, rootPath, None)
else:
target = targetPackageOrPath
if target.exists:
self._targets.append(target)
else:
csFiles = CoffeescriptBuilder.getScriptsInPath(target.packagePath)
# Look for exec matches first
for f in csFiles:
testTarget = CoffeescriptDependency(f, rootPath, None)
if testTarget.isExec:
self._targets.append(testTarget)
# Look for lib matches second. Lib matches are tested as a second pass because
# constructing all exec files first potentially optimizes the import process for
# the libraries.
for f in csFiles:
testTarget = CoffeescriptDependency(f, rootPath, None)
if testTarget.isLib:
self._targets.append(testTarget)
if len(self._targets) == 0:
print '\n\n'
self._log.write('No targets exist for: %s. Compilation aborted.' % targetPackageOrPath)
print '\n'
#===================================================================================================
# G E T / S E T
#___________________________________________________________________________________________________ GS: report
@property
def report(self):
return self._report
#___________________________________________________________________________________________________ GS: warnings
@property
def warnings(self):
return self._warnings
#___________________________________________________________________________________________________ GS: imports
@property
def imports(self):
return self._imports
#___________________________________________________________________________________________________ GS: requires
@property
def requires(self):
return self._requires
#___________________________________________________________________________________________________ GS: includes
@property
def includes(self):
return self._includes
#===================================================================================================
#.........这里部分代码省略.........
示例11: ResourceCollector
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class ResourceCollector(object):
"""A class for..."""
#===================================================================================================
# C L A S S
#___________________________________________________________________________________________________ __init__
def __init__(self, compiler, **kwargs):
"""Creates a new instance of ResourceCollector."""
self._log = Logger(self)
self._verbose = ArgsUtils.get('verbose', False, kwargs)
self._compiler = compiler
if OsUtils.isWindows():
self._targetPath = self._compiler.getBinPath('resources', isDir=True)
elif OsUtils.isMac():
self._targetPath = self._compiler.getBinPath('resources', 'resources', isDir=True)
if os.path.exists(self._targetPath):
shutil.rmtree(self._targetPath)
if not os.path.exists(self._targetPath):
os.makedirs(self._targetPath)
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ run
def run(self):
"""Doc..."""
resources = self._compiler.resources
#-------------------------------------------------------------------------------------------
# APP RESOURCES
# If no resource folders were specified copy the entire contents of the resources
# folder. Make sure to skip the local resources path in the process.
if not resources:
for item in os.listdir(PyGlassEnvironment.getRootResourcePath(isDir=True)):
itemPath = PyGlassEnvironment.getRootResourcePath(item)
if os.path.isdir(itemPath) and not item == 'local':
resources.append(item)
for container in resources:
parts = container.replace('\\', '/').split('/')
self._copyResourceFolder(
PyGlassEnvironment.getRootResourcePath(*parts, isDir=True), parts
)
#-------------------------------------------------------------------------------------------
# PYGLASS RESOURCES
# Copy the resources from the PyGlass
resources = []
for item in os.listdir(PyGlassEnvironment.getPyGlassResourcePath('..', isDir=True)):
itemPath = PyGlassEnvironment.getPyGlassResourcePath('..', item)
if os.path.isdir(itemPath):
resources.append(item)
for container in resources:
self._copyResourceFolder(
PyGlassEnvironment.getPyGlassResourcePath('..', container), [container]
)
#-------------------------------------------------------------------------------------------
# CLEANUP
if self._verbose:
self._log.write('CLEANUP: Removing unwanted destination files.')
self._cleanupFiles(self._targetPath)
self._copyPythonStaticResources()
if self._verbose:
self._log.write('COMPLETE: Resource Collection')
return True
#===================================================================================================
# P R O T E C T E D
#___________________________________________________________________________________________________ _copyResourceFolder
def _copyResourceFolder(self, sourcePath, parts):
targetPath = FileUtils.createPath(self._targetPath, *parts, isDir=True)
WidgetUiCompiler(sourcePath).run()
if self._verbose:
self._log.write('COPYING: %s -> %s' % (sourcePath, targetPath))
results = FileUtils.mergeCopy(sourcePath, targetPath)
#___________________________________________________________________________________________________ _copyPythonStaticResources
def _copyPythonStaticResources(self):
sourcePath = requests.utils.DEFAULT_CA_BUNDLE_PATH
parts = sourcePath[len(sys.exec_prefix):].strip(os.sep).split(os.sep)
destPath = FileUtils.createPath(self._targetPath, 'pythonRoot', *parts, isFile=True)
folder = os.path.dirname(destPath)
if not os.path.exists(folder):
os.makedirs(folder)
shutil.copy(sourcePath, destPath)
#___________________________________________________________________________________________________ _compilePythonFiles
#.........这里部分代码省略.........
示例12: TrackExporter
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class TrackExporter(object):
"""A class for..."""
#===============================================================================
# C L A S S
DELETED_IDENTIFIER = u'##DEL##'
#_______________________________________________________________________________
def __init__(self, logger =None):
"""Creates a new instance of TrackExporter."""
self.results = None
self.logger = logger
self.modifications = 0
if not logger:
self.logger = Logger(self, printOut=True)
#===============================================================================
# P U B L I C
#_______________________________________________________________________________
def process(self, session, difference =True):
"""Doc..."""
if self.results is not None:
return True
results = []
model = Tracks_Track.MASTER
if session is None:
session = model.createSession()
trackStores = session.query(model).all()
index = 0
indices = NumericUtils.linearSpace(0, len(trackStores), roundToIntegers=True)[1:]
for trackStore in trackStores:
track = trackStore.getMatchingTrack(session)
if track is None:
self.modifications += 1
results.append({'uid':trackStore.uid, 'action':self.DELETED_IDENTIFIER})
self.logger.write(
u'<div>DELETED: %s</div>' % DictUtils.prettyPrint(
trackStore.toDict(uniqueOnly=True)))
else:
if difference:
diff = trackStore.toDiffDict(track.toDict())
if diff is not None:
self.modifications += 1
results.append(diff)
self.logger.write(
u'<div>MODIFIED: %s</div>' % trackStore.fingerprint)
else:
results.append(track.toDict())
index += 1
if index in indices:
self.logger.write(
u'<div style="color:#33CC33">%s%% Complete</div>' % StringUtils.toUnicode(
10*(indices.index(index) + 1)))
self.logger.write(u'<div style="color:#33CC33">100% Complete</div>')
self.results = results
return True
#_______________________________________________________________________________
def write(self, session, path, pretty =False, gzipped =True, difference =True):
if self.results is None and not self.process(session, difference):
return False
try:
JSON.toFile(path, self.results, pretty=pretty, gzipped=gzipped, throwError=True)
return True
except Exception as err:
self.logger.writeError([
u'ERROR: Unable to write export file',
u'PATH: ' + StringUtils.toUnicode(path)], err)
return False
#===============================================================================
# I N T R I N S I C
#_______________________________________________________________________________
def __repr__(self):
return self.__str__()
#_______________________________________________________________________________
def __unicode__(self):
return StringUtils.toUnicode(self.__str__())
#_______________________________________________________________________________
def __str__(self):
return '<%s>' % self.__class__.__name__
示例13: WidgetUiCompiler
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class WidgetUiCompiler(object):
"""A class for..."""
#===================================================================================================
# C L A S S
_CLASS_NAME_RE = re.compile('(?<=class )(?P<classname>[a-zA-z0-9_]+)(?=\()')
_SETUP_UI_RE = re.compile('(?<=def setupUi\(self, )(?P<parentName>[a-zA-z0-9_\-]+)(?=\):)')
_RETRANSLATE_RE = re.compile(
'(?<=def retranslateUi\(self, )(?P<parentName>[a-zA-z0-9_\-]+)(?=\):)'
)
_SELF_RE = re.compile('(?P<self>self\.)(?!retranslateUi\()')
#___________________________________________________________________________________________________ __init__
def __init__(self, rootPath =None, recursive =True, **kwargs):
"""Creates a new instance of WidgetUiCompiler."""
self._log = Logger(self)
self._verbose = ArgsUtils.get('verbose', False, kwargs)
self._recursive = recursive
self._pythonPath = os.path.normpath(sys.exec_prefix)
if rootPath and os.path.isabs(rootPath):
self._rootPath = FileUtils.cleanupPath(rootPath, isDir=True)
elif rootPath:
parts = rootPath.split(os.sep if rootPath.find(os.sep) != -1 else '/')
self._rootPath = PyGlassEnvironment.getRootResourcePath(*parts, isDir=True)
else:
self._rootPath = PyGlassEnvironment.getRootResourcePath()
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ run
def run(self):
"""Doc..."""
arg = dict()
if self._recursive:
os.path.walk(self._rootPath, self._compileInFolder, arg)
else:
self._compileInFolder(arg, self._rootPath, os.listdir(self._rootPath))
#===================================================================================================
# P R O T E C T E D
#___________________________________________________________________________________________________ _compileInFolder
def _compileInFolder(self, arg, dirname, names):
for name in names:
if not name.endswith('.ui'):
continue
self._compileUiFile(dirname, name)
#___________________________________________________________________________________________________ _compileUiFile
def _compileUiFile(self, path, filename):
"""Doc..."""
source = FileUtils.createPath(path, filename, isFile=True)
if self._verbose:
self._log.write('COMPILING: ' + source)
if PyGlassEnvironment.isWindows:
uicCommand = FileUtils.createPath(self._pythonPath, 'Scripts', 'pyside-uic.exe')
else:
uicCommand = 'pyside-uic'
cmd = '%s %s' % (uicCommand, source)
pipe = subprocess.Popen(
cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, error = pipe.communicate()
if pipe.returncode or error:
self._log.write('ERROR: Failed to compile %s widget: %s' % (str(source), str(error)))
return False
res = WidgetUiCompiler._CLASS_NAME_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget class name for ' + str(source))
return False
out = WidgetUiCompiler._CLASS_NAME_RE.sub('PySideUiFileSetup', out, 1)
res = WidgetUiCompiler._SETUP_UI_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget setupUi method for ' + str(source))
return False
targetName = res.groupdict().get('parentName')
out = WidgetUiCompiler._SETUP_UI_RE.sub('\g<parentName>', out, 1)
res = WidgetUiCompiler._RETRANSLATE_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget retranslateUi method for ' + str(source))
return False
out = WidgetUiCompiler._RETRANSLATE_RE.sub('\g<parentName>', out, 1)
#.........这里部分代码省略.........
示例14: DataFormatConverter
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
class DataFormatConverter(object):
"""A class for converting between various data interchange formats, e.g. XML and JSON."""
#===================================================================================================
# C L A S S
#___________________________________________________________________________________________________ __init__
def __init__(self):
"""Creates a new instance of ClassTemplate."""
self._type = None
self._src = None
self._log = Logger('DataFormatConverter')
self._path = None
#===================================================================================================
# G E T / S E T
#___________________________________________________________________________________________________ GS: propertyName
@property
def source(self):
return self._src
#===================================================================================================
# P U B L I C
#___________________________________________________________________________________________________ load
def load(self, path, fileType):
if not os.path.exists(path):
self._log.write('ERROR: Path does not exist [%s]. Unable to load.' % path)
return False
try:
fh = codecs.open(path, 'r', 'utf-8')
res = fh.read()
fh.close()
enc = res.encode('utf-8')
self.loads(enc, fileType)
except Exception as err:
self._log.writeError('Failed to load source file [%s].' % path, err)
return False
self._path = path
return True
#___________________________________________________________________________________________________ load
def loads(self, srcString, srcType):
if srcString is None:
self._log.write('ERROR: Source string is empty or invalid.')
return False
srcString = StringUtils.toStr2(srcString)
self._path = None
self._src = srcString
self._type = srcType
return True
#___________________________________________________________________________________________________ convertDirectory
def convertDirectory(self, path, srcType, targetType, recursive =False):
if srcType is None or targetType is None:
self._log.write('ERROR: Source and/or target types are invalid. Operation aborted.')
return False
if not os.path.exists(path):
self._log.write('ERROR: The specified path [%s] does not exist. Operation aborted.' \
% str(path))
return False
if recursive:
FileUtils.walkPath(path, self._convertInDirectory, [srcType, targetType])
else:
self._convertInDirectory([srcType, targetType], path, os.listdir(path))
return True
#___________________________________________________________________________________________________ writeToFile
def writeToFile(self, targetType, path =None):
if path is None and self._path is None:
self._log.write('ERROR: Unable to write to file, no path was specified.')
return False
# Assign the reader based on source type
reader = self._getParserFromType()
if reader is None:
self._log.write('ERROR: Unrecognized source type [%s]. Unable to convert.' % self._type)
return False
# Assign writer based on target type
writer = self._getParserFromType(targetType)
if writer is None:
self._log.write('ERROR: Unrecognized conversion target type [%s]. Unable to convert.' \
% targetType)
return False
path = path if path else self._path
d = os.path.dirname(path)
f = os.path.basename(path).split('.')[0]
f += '.' + writer.TYPE_ID
if not os.path.exists(d):
#.........这里部分代码省略.........
示例15: populateTrackwaysTable
# 需要导入模块: from pyaid.debug.Logger import Logger [as 别名]
# 或者: from pyaid.debug.Logger.Logger import write [as 别名]
def populateTrackwaysTable(cls, session =None, logger =None):
""" Populate the trackways table by removing all existing rows and
attempting to calculate trackways from the implicit track series
defined by the linkages of tracks. This operation should only be
carried out for initial population purposes as it will dispose of
all existing data and changes made by users. """
from cadence.models.tracks.Tracks_Track import Tracks_Track
from cadence.models.tracks.Tracks_SiteMap import Tracks_SiteMap
missingSitemaps = []
sitemapModel = Tracks_SiteMap.MASTER
trackModel = Tracks_Track.MASTER
model = cls.MASTER
if not logger:
logger = Logger(cls, printOut=True)
newSession = False
if not session:
newSession = True
session = model.createSession()
# Get all tracks that have no next (end of a track series)
endTracks = session.query(trackModel).filter(
trackModel.next == '').all()
index = 0
trackways = dict()
tested = []
for track in endTracks:
if track in tested or track.hidden:
# Skip tracks that have already been tested or are hidden
continue
prev = track
while prev:
tested.append(prev)
t = prev.getPreviousTrack()
if not t:
break
prev = t
if not prev:
continue
name = prev.trackwayFingerprint
sitemapStamp = '%s-%s' % (prev.site, prev.level)
if sitemapStamp in missingSitemaps:
# Ignore the trackway if there's no sitemap to support it
continue
if name in trackways:
tw = trackways[name]
else:
# If the trackway name isn't in the list of existing trackways,
# create a new trackway model instance for that trackway
tw = Tracks_Trackway()
tw.index = index
tw.name = name
sitemap = session.query(sitemapModel).filter(
sitemapModel.name == prev.site).filter(
sitemapModel.level == prev.level).first()
if not sitemap:
missingSitemaps.append(sitemapStamp)
logger.write(
'[WARNING]: No site map found for "%s" level "%s"' % (
prev.site, prev.level))
else:
tw.siteMapIndex = sitemap.index
index += 1
trackways[tw.name] = tw
if prev.left and prev.pes:
existing = tw.firstLeftPes
tw.firstLeftPes = prev.uid
elif prev.left:
existing = tw.firstLeftManus
tw.firstLeftManus = prev.uid
elif prev.pes:
existing = tw.firstRightPes
tw.firstRightPes = prev.uid
else:
existing = tw.firstRightManus
tw.firstRightManus = prev.uid
if existing and existing != prev.uid:
logger.write([
'[WARNING]: Duplicate tracks found for the same series',
'TRACKS: "%s" AND "%s"' % (existing, prev.uid),
'TRACKWAY: %s' % tw.name])
# Delete all existing rows if any exist
rowCount = session.query(model).count()
if rowCount > 0:
#.........这里部分代码省略.........