Migrate python2 code to python3:

Updated all required lines which contains 'print'
    Updated all required lines which contains 'except'
This commit is contained in:
Serge Rabyking 2023-05-19 17:42:22 +01:00
parent d41e328253
commit 41e57a7512
21 changed files with 275 additions and 275 deletions

View File

@ -11,8 +11,8 @@ if __name__ == "__main__":
try: try:
scriptPath = os.path.abspath( os.path.dirname(sys.argv[0]) ) scriptPath = os.path.abspath( os.path.dirname(sys.argv[0]) )
print 'buildCoriolis.py is run from:' print('buildCoriolis.py is run from:')
print ' <%s>' % scriptPath print(' <%s>' % scriptPath)
parser = optparse.OptionParser () parser = optparse.OptionParser ()
# Build relateds. # Build relateds.
@ -80,11 +80,11 @@ if __name__ == "__main__":
elif options.doRpm: builder.doRpm () elif options.doRpm: builder.doRpm ()
elif options.doDeb: builder.doDeb () elif options.doDeb: builder.doDeb ()
else: builder.build ( tools=options.tools, projects=options.projects ) else: builder.build ( tools=options.tools, projects=options.projects )
except ErrorMessage, e: except ErrorMessage as e:
print e print(e)
sys.exit(e.code) sys.exit(e.code)
#except Exception, e: #except Exception as e:
# print e # print(e)
# sys.exit(1) # sys.exit(1)
sys.exit ( 0 ) sys.exit ( 0 )

View File

@ -39,7 +39,7 @@ try:
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication from email.mime.application import MIMEApplication
except ImportError, e: except ImportError as e:
module = str(e).split()[-1] module = str(e).split()[-1]
@ -94,7 +94,7 @@ class ErrorMessage ( Exception ):
return return
def terminate ( self ): def terminate ( self ):
print self print(self)
sys.exit(self._code) sys.exit(self._code)
@property @property
@ -122,7 +122,7 @@ class Command ( object ):
self.fdLog = fdLog self.fdLog = fdLog
if self.fdLog != None and not isinstance(self.fdLog,file): if self.fdLog != None and not isinstance(self.fdLog,file):
print '[WARNING] Command.__init__(): <fdLog> is neither None or a file.' print('[WARNING] Command.__init__(): <fdLog> is neither None or a file.')
return return
def _argumentsToStr ( self, arguments ): def _argumentsToStr ( self, arguments ):
@ -133,7 +133,7 @@ class Command ( object ):
return s return s
def log ( self, text ): def log ( self, text ):
print text[:-1] print(text[:-1])
sys.stdout.flush() sys.stdout.flush()
sys.stderr.flush() sys.stderr.flush()
if isinstance(self.fdLog,file): if isinstance(self.fdLog,file):
@ -151,12 +151,12 @@ class Command ( object ):
if homeDir.startswith(homeDir): if homeDir.startswith(homeDir):
workDir = '~' + workDir[ len(homeDir) : ] workDir = '~' + workDir[ len(homeDir) : ]
user = 'root' user = 'root'
if os.environ.has_key('USER'): user = os.environ['USER'] if 'USER' in os.environ: user = os.environ['USER']
prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir) prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir)
try: try:
self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) ) self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) )
print self.arguments print(self.arguments)
child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
while True: while True:
@ -164,7 +164,7 @@ class Command ( object ):
if not line: break if not line: break
self.log( line ) self.log( line )
except OSError, e: except OSError as e:
raise BadBinary( self.arguments[0] ) raise BadBinary( self.arguments[0] )
(pid,status) = os.waitpid( child.pid, 0 ) (pid,status) = os.waitpid( child.pid, 0 )
@ -258,12 +258,12 @@ class GitRepository ( object ):
def removeLocalRepo ( self ): def removeLocalRepo ( self ):
if os.path.isdir(self.localRepoDir): if os.path.isdir(self.localRepoDir):
print 'Removing Git local repository: <%s>' % self.localRepoDir print('Removing Git local repository: <%s>' % self.localRepoDir)
shutil.rmtree( self.localRepoDir ) shutil.rmtree( self.localRepoDir )
return return
def clone ( self ): def clone ( self ):
print 'Clone/pull from:', self.url print('Clone/pull from:', self.url)
if not os.path.isdir(self.cloneDir): if not os.path.isdir(self.cloneDir):
os.makedirs( self.cloneDir ) os.makedirs( self.cloneDir )
@ -329,12 +329,12 @@ class Configuration ( object ):
def __setattr__ ( self, attribute, value ): def __setattr__ ( self, attribute, value ):
if attribute in Configuration.SecondaryNames: if attribute in Configuration.SecondaryNames:
print ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ) print(ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ))
return return
if attribute == 'masterHost' or attribute == '_masterHost': if attribute == 'masterHost' or attribute == '_masterHost':
if value == 'lepka': if value == 'lepka':
print 'Never touch the Git tree when running on <lepka>.' print('Never touch the Git tree when running on <lepka>.')
self._rmSource = False self._rmSource = False
self._rmBuild = False self._rmBuild = False
self._doGit = False self._doGit = False
@ -393,7 +393,7 @@ class Configuration ( object ):
while True: while True:
logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index)) logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index))
if not os.path.isfile(logFile): if not os.path.isfile(logFile):
print "Report log: <%s>" % logFile print("Report log: <%s>" % logFile)
break break
index += 1 index += 1
fd = open( logFile, "w" ) fd = open( logFile, "w" )
@ -506,7 +506,7 @@ class Report ( object ):
fd = open( logFile, 'rb' ) fd = open( logFile, 'rb' )
try: try:
fd.seek( -1024*100, os.SEEK_END ) fd.seek( -1024*100, os.SEEK_END )
except IOError, e: except IOError as e:
pass pass
tailLines = '' tailLines = ''
for line in fd.readlines()[1:]: for line in fd.readlines()[1:]:
@ -525,8 +525,8 @@ class Report ( object ):
for attachement in self.attachements: for attachement in self.attachements:
self.message.attach( attachement ) self.message.attach( attachement )
print "Sending mail report to:" print("Sending mail report to:")
for receiver in self.conf.receivers: print ' <%s>' % receiver for receiver in self.conf.receivers: print(' <%s>' % receiver)
session = smtplib.SMTP( 'localhost' ) session = smtplib.SMTP( 'localhost' )
session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() ) session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() )
session.quit() session.quit()
@ -613,29 +613,29 @@ try:
for entry in os.listdir(conf.rootDir): for entry in os.listdir(conf.rootDir):
if entry.startswith('Linux.'): if entry.startswith('Linux.'):
buildDir = conf.rootDir+'/'+entry buildDir = conf.rootDir+'/'+entry
print 'Removing OS build directory: <%s>' % buildDir print('Removing OS build directory: <%s>' % buildDir)
shutil.rmtree( buildDir ) shutil.rmtree( buildDir )
commands = conf.getCommands( options.profile ) commands = conf.getCommands( options.profile )
for command in commands: for command in commands:
if command.host: if command.host:
print 'Executing command on remote host <%s>:' % host print('Executing command on remote host <%s>:' % host)
else: else:
print 'Executing command on *local* host:' print('Executing command on *local* host:')
print ' %s' % str(command) print(' %s' % str(command))
command.execute() command.execute()
conf.closeLogs() conf.closeLogs()
conf.success = True conf.success = True
except ErrorMessage, e: except ErrorMessage as e:
print e print(e)
conf.closeLogs() conf.closeLogs()
conf.success = False conf.success = False
if showTrace: if showTrace:
print '\nPython stack trace:' print('\nPython stack trace:')
traceback.print_tb( sys.exc_info()[2] ) traceback.print_tb( sys.exc_info()[2] )
conf.rcode = e.code conf.rcode = e.code

View File

@ -39,7 +39,7 @@ try:
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication from email.mime.application import MIMEApplication
except ImportError, e: except ImportError as e:
module = str(e).split()[-1] module = str(e).split()[-1]
@ -94,7 +94,7 @@ class ErrorMessage ( Exception ):
return return
def terminate ( self ): def terminate ( self ):
print self print(self)
sys.exit(self._code) sys.exit(self._code)
@property @property
@ -122,7 +122,7 @@ class Command ( object ):
self.fdLog = fdLog self.fdLog = fdLog
if self.fdLog != None and not isinstance(self.fdLog,file): if self.fdLog != None and not isinstance(self.fdLog,file):
print '[WARNING] Command.__init__(): <fdLog> is neither None or a file.' print('[WARNING] Command.__init__(): <fdLog> is neither None or a file.')
return return
def _argumentsToStr ( self, arguments ): def _argumentsToStr ( self, arguments ):
@ -133,7 +133,7 @@ class Command ( object ):
return s return s
def log ( self, text ): def log ( self, text ):
print text[:-1] print(text[:-1])
sys.stdout.flush() sys.stdout.flush()
sys.stderr.flush() sys.stderr.flush()
if isinstance(self.fdLog,file): if isinstance(self.fdLog,file):
@ -151,12 +151,12 @@ class Command ( object ):
if homeDir.startswith(homeDir): if homeDir.startswith(homeDir):
workDir = '~' + workDir[ len(homeDir) : ] workDir = '~' + workDir[ len(homeDir) : ]
user = 'root' user = 'root'
if os.environ.has_key('USER'): user = os.environ['USER'] if 'USER' in os.environ: user = os.environ['USER']
prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir) prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir)
try: try:
self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) ) self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) )
print self.arguments print(self.arguments)
child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
while True: while True:
@ -164,7 +164,7 @@ class Command ( object ):
if not line: break if not line: break
self.log( line ) self.log( line )
except OSError, e: except OSError as e:
raise BadBinary( self.arguments[0] ) raise BadBinary( self.arguments[0] )
(pid,status) = os.waitpid( child.pid, 0 ) (pid,status) = os.waitpid( child.pid, 0 )
@ -251,12 +251,12 @@ class GitRepository ( object ):
def removeLocalRepo ( self ): def removeLocalRepo ( self ):
if os.path.isdir(self.localRepoDir): if os.path.isdir(self.localRepoDir):
print 'Removing Git local repository: <%s>' % self.localRepoDir print('Removing Git local repository: <%s>' % self.localRepoDir)
shutil.rmtree( self.localRepoDir ) shutil.rmtree( self.localRepoDir )
return return
def clone ( self ): def clone ( self ):
print 'Clone/pull from:', self.url print('Clone/pull from:', self.url)
if not os.path.isdir(self.cloneDir): if not os.path.isdir(self.cloneDir):
os.makedirs( self.cloneDir ) os.makedirs( self.cloneDir )
@ -321,12 +321,12 @@ class Configuration ( object ):
def __setattr__ ( self, attribute, value ): def __setattr__ ( self, attribute, value ):
if attribute in Configuration.SecondaryNames: if attribute in Configuration.SecondaryNames:
print ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ) print(ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ))
return return
if attribute == 'masterHost' or attribute == '_masterHost': if attribute == 'masterHost' or attribute == '_masterHost':
if value == 'lepka': if value == 'lepka':
print 'Never touch the Git tree when running on <lepka>.' print('Never touch the Git tree when running on <lepka>.')
self._rmSource = False self._rmSource = False
self._rmBuild = False self._rmBuild = False
self._doGit = False self._doGit = False
@ -384,7 +384,7 @@ class Configuration ( object ):
while True: while True:
logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index)) logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index))
if not os.path.isfile(logFile): if not os.path.isfile(logFile):
print "Report log: <%s>" % logFile print("Report log: <%s>" % logFile)
break break
index += 1 index += 1
fd = open( logFile, "w" ) fd = open( logFile, "w" )
@ -490,7 +490,7 @@ class Report ( object ):
fd = open( logFile, 'rb' ) fd = open( logFile, 'rb' )
try: try:
fd.seek( -1024*100, os.SEEK_END ) fd.seek( -1024*100, os.SEEK_END )
except IOError, e: except IOError as e:
pass pass
tailLines = '' tailLines = ''
for line in fd.readlines()[1:]: for line in fd.readlines()[1:]:
@ -509,8 +509,8 @@ class Report ( object ):
for attachement in self.attachements: for attachement in self.attachements:
self.message.attach( attachement ) self.message.attach( attachement )
print "Sending mail report to:" print("Sending mail report to:")
for receiver in self.conf.receivers: print ' <%s>' % receiver for receiver in self.conf.receivers: print(' <%s>' % receiver)
session = smtplib.SMTP( 'localhost' ) session = smtplib.SMTP( 'localhost' )
session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() ) session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() )
session.quit() session.quit()
@ -594,29 +594,29 @@ try:
for entry in os.listdir(conf.rootDir): for entry in os.listdir(conf.rootDir):
if entry.startswith('Linux.'): if entry.startswith('Linux.'):
buildDir = conf.rootDir+'/'+entry buildDir = conf.rootDir+'/'+entry
print 'Removing OS build directory: <%s>' % buildDir print('Removing OS build directory: <%s>' % buildDir)
shutil.rmtree( buildDir ) shutil.rmtree( buildDir )
commands = conf.getCommands( options.profile ) commands = conf.getCommands( options.profile )
for command in commands: for command in commands:
if command.host: if command.host:
print 'Executing command on remote host <%s>:' % host print('Executing command on remote host <%s>:' % host)
else: else:
print 'Executing command on *local* host:' print('Executing command on *local* host:')
print ' %s' % str(command) print(' %s' % str(command))
command.execute() command.execute()
conf.closeLogs() conf.closeLogs()
conf.success = True conf.success = True
except ErrorMessage, e: except ErrorMessage as e:
print e print(e)
conf.closeLogs() conf.closeLogs()
conf.success = False conf.success = False
if showTrace: if showTrace:
print '\nPython stack trace:' print('\nPython stack trace:')
traceback.print_tb( sys.exc_info()[2] ) traceback.print_tb( sys.exc_info()[2] )
conf.rcode = e.code conf.rcode = e.code

View File

@ -39,7 +39,7 @@ try:
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication from email.mime.application import MIMEApplication
except ImportError, e: except ImportError as e:
module = str(e).split()[-1] module = str(e).split()[-1]
@ -94,7 +94,7 @@ class ErrorMessage ( Exception ):
return return
def terminate ( self ): def terminate ( self ):
print self print(self)
sys.exit(self._code) sys.exit(self._code)
@property @property
@ -122,7 +122,7 @@ class Command ( object ):
self.fdLog = fdLog self.fdLog = fdLog
if self.fdLog != None and not isinstance(self.fdLog,file): if self.fdLog != None and not isinstance(self.fdLog,file):
print '[WARNING] Command.__init__(): <fdLog> is neither None or a file.' print('[WARNING] Command.__init__(): <fdLog> is neither None or a file.')
return return
def _argumentsToStr ( self, arguments ): def _argumentsToStr ( self, arguments ):
@ -133,7 +133,7 @@ class Command ( object ):
return s return s
def log ( self, text ): def log ( self, text ):
print text[:-1] print(text[:-1])
sys.stdout.flush() sys.stdout.flush()
sys.stderr.flush() sys.stderr.flush()
if isinstance(self.fdLog,file): if isinstance(self.fdLog,file):
@ -151,12 +151,12 @@ class Command ( object ):
if homeDir.startswith(homeDir): if homeDir.startswith(homeDir):
workDir = '~' + workDir[ len(homeDir) : ] workDir = '~' + workDir[ len(homeDir) : ]
user = 'root' user = 'root'
if os.environ.has_key('USER'): user = os.environ['USER'] if 'USER' in os.environ: user = os.environ['USER']
prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir) prompt = '%s@%s:%s$' % (user,conf.masterHost,workDir)
try: try:
self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) ) self.log( '%s%s\n' % (prompt,self._argumentsToStr(self.arguments)) )
print self.arguments print(self.arguments)
child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) child = subprocess.Popen( self.arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
while True: while True:
@ -164,7 +164,7 @@ class Command ( object ):
if not line: break if not line: break
self.log( line ) self.log( line )
except OSError, e: except OSError as e:
raise BadBinary( self.arguments[0] ) raise BadBinary( self.arguments[0] )
(pid,status) = os.waitpid( child.pid, 0 ) (pid,status) = os.waitpid( child.pid, 0 )
@ -258,12 +258,12 @@ class GitRepository ( object ):
def removeLocalRepo ( self ): def removeLocalRepo ( self ):
if os.path.isdir(self.localRepoDir): if os.path.isdir(self.localRepoDir):
print 'Removing Git local repository: <%s>' % self.localRepoDir print('Removing Git local repository: <%s>' % self.localRepoDir)
shutil.rmtree( self.localRepoDir ) shutil.rmtree( self.localRepoDir )
return return
def clone ( self ): def clone ( self ):
print 'Clone/pull from:', self.url print('Clone/pull from:', self.url)
if not os.path.isdir(self.cloneDir): if not os.path.isdir(self.cloneDir):
os.makedirs( self.cloneDir ) os.makedirs( self.cloneDir )
@ -329,12 +329,12 @@ class Configuration ( object ):
def __setattr__ ( self, attribute, value ): def __setattr__ ( self, attribute, value ):
if attribute in Configuration.SecondaryNames: if attribute in Configuration.SecondaryNames:
print ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ) print(ErrorMessage( 1, 'Attempt to write in read-only attribute <%s> in Configuration.'%attribute ))
return return
if attribute == 'masterHost' or attribute == '_masterHost': if attribute == 'masterHost' or attribute == '_masterHost':
if value == 'lepka': if value == 'lepka':
print 'Never touch the Git tree when running on <lepka>.' print('Never touch the Git tree when running on <lepka>.')
self._rmSource = False self._rmSource = False
self._rmBuild = False self._rmBuild = False
self._doGit = False self._doGit = False
@ -393,7 +393,7 @@ class Configuration ( object ):
while True: while True:
logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index)) logFile = os.path.join(self._logDir,"%s-%s-%02d.log" % (stem,timeTag,index))
if not os.path.isfile(logFile): if not os.path.isfile(logFile):
print "Report log: <%s>" % logFile print("Report log: <%s>" % logFile)
break break
index += 1 index += 1
fd = open( logFile, "w" ) fd = open( logFile, "w" )
@ -506,7 +506,7 @@ class Report ( object ):
fd = open( logFile, 'rb' ) fd = open( logFile, 'rb' )
try: try:
fd.seek( -1024*100, os.SEEK_END ) fd.seek( -1024*100, os.SEEK_END )
except IOError, e: except IOError as e:
pass pass
tailLines = '' tailLines = ''
for line in fd.readlines()[1:]: for line in fd.readlines()[1:]:
@ -525,8 +525,8 @@ class Report ( object ):
for attachement in self.attachements: for attachement in self.attachements:
self.message.attach( attachement ) self.message.attach( attachement )
print "Sending mail report to:" print("Sending mail report to:")
for receiver in self.conf.receivers: print ' <%s>' % receiver for receiver in self.conf.receivers: print(' <%s>' % receiver)
session = smtplib.SMTP( 'localhost' ) session = smtplib.SMTP( 'localhost' )
session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() ) session.sendmail( self.conf.sender, self.conf.receivers, self.message.as_string() )
session.quit() session.quit()
@ -613,29 +613,29 @@ try:
for entry in os.listdir(conf.rootDir): for entry in os.listdir(conf.rootDir):
if entry.startswith('Linux.'): if entry.startswith('Linux.'):
buildDir = conf.rootDir+'/'+entry buildDir = conf.rootDir+'/'+entry
print 'Removing OS build directory: <%s>' % buildDir print('Removing OS build directory: <%s>' % buildDir)
shutil.rmtree( buildDir ) shutil.rmtree( buildDir )
commands = conf.getCommands( options.profile ) commands = conf.getCommands( options.profile )
for command in commands: for command in commands:
if command.host: if command.host:
print 'Executing command on remote host <%s>:' % host print('Executing command on remote host <%s>:' % host)
else: else:
print 'Executing command on *local* host:' print('Executing command on *local* host:')
print ' %s' % str(command) print(' %s' % str(command))
command.execute() command.execute()
conf.closeLogs() conf.closeLogs()
conf.success = True conf.success = True
except ErrorMessage, e: except ErrorMessage as e:
print e print(e)
conf.closeLogs() conf.closeLogs()
conf.success = False conf.success = False
if showTrace: if showTrace:
print '\nPython stack trace:' print('\nPython stack trace:')
traceback.print_tb( sys.exc_info()[2] ) traceback.print_tb( sys.exc_info()[2] )
conf.rcode = e.code conf.rcode = e.code

View File

@ -57,8 +57,8 @@ def guessOs ():
uname = subprocess.Popen ( ["uname", "-sr"], stdout=subprocess.PIPE ) uname = subprocess.Popen ( ["uname", "-sr"], stdout=subprocess.PIPE )
osType = uname.stdout.readlines()[0][:-1] osType = uname.stdout.readlines()[0][:-1]
#print "[WARNING] Unrecognized OS: \"%s\"." % lines[0][:-1] #print("[WARNING] Unrecognized OS: \"%s\"." % lines[0][:-1])
#print " (using: \"%s\")" % osType #print(" (using: \"%s\")" % osType)
return (osType,libDir) return (osType,libDir)
@ -118,10 +118,10 @@ export PATH LD_LIBRARY_PATH PYTHONPATH BOOTSTRAP_TOP CORIOLIS_TOP MANGROVE_TOP;
hash -r hash -r
""" """
print shellScript % { "PATH" : strippedPath print(shellScript % { "PATH" : strippedPath
, "LD_LIBRARY_PATH" : strippedLibraryPath , "LD_LIBRARY_PATH" : strippedLibraryPath
, "PYTHONPATH" : strippedPythonPath , "PYTHONPATH" : strippedPythonPath
, "CORIOLIS_TOP" : sysCoriolisTop , "CORIOLIS_TOP" : sysCoriolisTop
, "MANGROVE_TOP" : mangroveTop , "MANGROVE_TOP" : mangroveTop
, "buildDir" : buildDir , "buildDir" : buildDir
} })

View File

@ -57,7 +57,7 @@ class Refactor:
m = refactorPattern.match( line ) m = refactorPattern.match( line )
if m: if m:
print "o:\"%s\" r:\"%s\"" % ( m.group("orig"), m.group("replace") ) print("o:\"%s\" r:\"%s\"" % ( m.group("orig"), m.group("replace") ))
self._addRefactor( m.group("orig"), m.group("replace") ) self._addRefactor( m.group("orig"), m.group("replace") )
fd.close () fd.close ()
return return
@ -92,7 +92,7 @@ if __name__ == '__main__' :
allFiles += rfiles allFiles += rfiles
for file in allFiles: for file in allFiles:
print file print(file)
refactor.doFileRefactor( file ) refactor.doFileRefactor( file )
sys.exit( 0 ) sys.exit( 0 )

View File

@ -12,7 +12,7 @@ soPathName = sys.argv[1]
soFileName = os.path.basename( soPathName ) soFileName = os.path.basename( soPathName )
profName = soFileName + '.profile' profName = soFileName + '.profile'
if not os.path.isfile(profName): if not os.path.isfile(profName):
print '[ERROR] No profile datas <%s>.' % profName print('[ERROR] No profile datas <%s>.' % profName)
sys.exit( 1 ) sys.exit( 1 )
sprof = subprocess.Popen ( ['sprof' sprof = subprocess.Popen ( ['sprof'
@ -30,8 +30,8 @@ for line in sprof.stdout.readlines():
, stdout=subprocess.PIPE ) , stdout=subprocess.PIPE )
symbol = cppfilt.stdout.readlines()[0][:-1] symbol = cppfilt.stdout.readlines()[0][:-1]
print m.group('head'), symbol print(m.group('head'), symbol)
else: else:
print line[:-1] print(line[:-1])
sys.exit( 0 ) sys.exit( 0 )

View File

@ -16,7 +16,7 @@ try:
import Viewer import Viewer
import CRL import CRL
import plugins.rsave import plugins.rsave
except Exception, e: except Exception as e:
catch( e ) catch( e )
sys.exit(2) sys.exit(2)

View File

@ -34,7 +34,7 @@ try:
import helpers import helpers
from helpers import trace from helpers import trace
from helpers.io import ErrorMessage from helpers.io import ErrorMessage
except ImportError, e: except ImportError as e:
serror = str(e) serror = str(e)
if serror.startswith('No module named'): if serror.startswith('No module named'):
module = serror.split()[-1] module = serror.split()[-1]
@ -46,7 +46,7 @@ except ImportError, e:
print( ' Under RHEL 6, you must be under devtoolset-2.' ) print( ' Under RHEL 6, you must be under devtoolset-2.' )
print( ' (scl enable devtoolset-2 bash)' ) print( ' (scl enable devtoolset-2 bash)' )
sys.exit(1) sys.exit(1)
except Exception, e: except Exception as e:
print( '[ERROR] A strange exception occurred while loading the basic Coriolis/Python' ) print( '[ERROR] A strange exception occurred while loading the basic Coriolis/Python' )
print( ' modules. Something may be wrong at Python/C API level.\n' ) print( ' modules. Something may be wrong at Python/C API level.\n' )
print( ' {}'.format(e) ) print( ' {}'.format(e) )
@ -120,7 +120,7 @@ def px2mpx ( editor, pxCell ):
if pxCell == None: if pxCell == None:
raise ErrorMessage( 3, 'px2mpx.px2mpx(): Mandatory pxCell argument is None.' ) raise ErrorMessage( 3, 'px2mpx.px2mpx(): Mandatory pxCell argument is None.' )
mpxCell = None mpxCell = None
print '\nProcessing', pxCell print('\nProcessing', pxCell)
UpdateSession.open() UpdateSession.open()
try: try:
@ -163,7 +163,7 @@ def px2mpx ( editor, pxCell ):
layer = component.getLayer() layer = component.getLayer()
dupComponent = None dupComponent = None
print ' Processing', component print(' Processing', component)
if isinstance(component,Contact): if isinstance(component,Contact):
dupComponent = Contact.create( mpxNet dupComponent = Contact.create( mpxNet
@ -183,21 +183,21 @@ def px2mpx ( editor, pxCell ):
if component.getSourceX() > component.getTargetX(): component.invert() if component.getSourceX() > component.getTargetX(): component.invert()
if isinstance(layer,RegularLayer): if isinstance(layer,RegularLayer):
if layer.getBasicLayer().getMaterial().getCode() == BasicLayer.Material.blockage: if layer.getBasicLayer().getMaterial().getCode() == BasicLayer.Material.blockage:
print ' Blockage BB:%s vs. AB:%s' % (bb, ab) print(' Blockage BB:%s vs. AB:%s' % (bb, ab))
if layer.getName()[-1] == '2' or layer.getName()[-1] == '4': if layer.getName()[-1] == '2' or layer.getName()[-1] == '4':
state = 0 state = 0
if bb.getXMin() <= ab.getXMin(): state |= Left if bb.getXMin() <= ab.getXMin(): state |= Left
if bb.getXMax() >= ab.getXMax(): state |= Right if bb.getXMax() >= ab.getXMax(): state |= Right
if not (state&Left): if not (state&Left):
print ' Shrink left.' print(' Shrink left.')
dLLeft = dL - DbU.fromLambda( 1.5 ) dLLeft = dL - DbU.fromLambda( 1.5 )
if not(state&Right): if not(state&Right):
print ' Shrink right.' print(' Shrink right.')
dLRight = dL - DbU.fromLambda( 1.5 ) dLRight = dL - DbU.fromLambda( 1.5 )
if layer.getName()[-1] == '4' and state == AllSpan: if layer.getName()[-1] == '4' and state == AllSpan:
print ' Skipping component.' print(' Skipping component.')
skipComponent = True skipComponent = True
width = mW width = mW
@ -213,9 +213,9 @@ def px2mpx ( editor, pxCell ):
, component.getDxSource()*2 - dLLeft , component.getDxSource()*2 - dLLeft
, component.getDxTarget()*2 + dLRight , component.getDxTarget()*2 + dLRight
) )
print ' Copy:', dupComponent print(' Copy:', dupComponent)
else: else:
print ' Horizontal component too small *or* skipped, not converted' print(' Horizontal component too small *or* skipped, not converted')
elif isinstance(component,Vertical): elif isinstance(component,Vertical):
dL, dW, mW = getDeltas( component.getLayer() ) dL, dW, mW = getDeltas( component.getLayer() )
@ -245,7 +245,7 @@ def px2mpx ( editor, pxCell ):
if layer.getName()[-1] == '5': if layer.getName()[-1] == '5':
if state == AllSpan: if state == AllSpan:
print ' Skipping component.' print(' Skipping component.')
skipComponent = True skipComponent = True
else: else:
dLTop = DbU.fromLambda(120.0) - component.getDyTarget()*2 dLTop = DbU.fromLambda(120.0) - component.getDyTarget()*2
@ -263,20 +263,20 @@ def px2mpx ( editor, pxCell ):
, component.getDyTarget()*2 + dLTop , component.getDyTarget()*2 + dLTop
) )
else: else:
print ' Vertical component too small *or* skipped, not converted' print(' Vertical component too small *or* skipped, not converted')
else: else:
print '[WARNING] Unchanged component:', component print('[WARNING] Unchanged component:', component)
if dupComponent and NetExternalComponents.isExternal( component ): if dupComponent and NetExternalComponents.isExternal( component ):
NetExternalComponents.setExternal( dupComponent ) NetExternalComponents.setExternal( dupComponent )
if editor: editor.fit() if editor: editor.fit()
except ErrorMessage, e: except ErrorMessage as e:
print e; errorCode = e.code print(e); errorCode = e.code
except Exception, e: except Exception as e:
print '\n\n', e; errorCode = 1 print('\n\n', e); errorCode = 1
traceback.print_tb(sys.exc_info()[2]) traceback.print_tb(sys.exc_info()[2])
UpdateSession.close() UpdateSession.close()
@ -297,7 +297,7 @@ def scriptMain ( **kw ):
editor = None editor = None
if kw.has_key('editor') and kw['editor']: if kw.has_key('editor') and kw['editor']:
editor = kw['editor'] editor = kw['editor']
print ' o Editor detected, running in graphic mode.' print(' o Editor detected, running in graphic mode.')
if pxCell == None: pxCell = editor.getCell() if pxCell == None: pxCell = editor.getCell()
if pxCell: if pxCell:
@ -306,7 +306,7 @@ def scriptMain ( **kw ):
pxlibDir = '/dsk/l1/jpc/alliance/Linux.slsoc6x/install/cells/pxlib' pxlibDir = '/dsk/l1/jpc/alliance/Linux.slsoc6x/install/cells/pxlib'
if os.path.isdir(pxlibDir): if os.path.isdir(pxlibDir):
print ' o <%s> found.' % pxlibDir print(' o <%s> found.' % pxlibDir)
for viewFile in os.listdir( pxlibDir ): for viewFile in os.listdir( pxlibDir ):
if viewFile == 'padreal.ap': if viewFile == 'padreal.ap':
pxCell = framework.getCell( viewFile[:-3], CRL.Catalog.State.Views ) pxCell = framework.getCell( viewFile[:-3], CRL.Catalog.State.Views )
@ -323,7 +323,7 @@ def scriptMain ( **kw ):
mpxCell = px2mpx( editor, pxCell ) mpxCell = px2mpx( editor, pxCell )
framework.saveCell( mpxCell, CRL.Catalog.State.Physical ) framework.saveCell( mpxCell, CRL.Catalog.State.Physical )
else: else:
print '[WARNING] <%s> not found.' % pxlibDir print('[WARNING] <%s> not found.' % pxlibDir)
return 0 return 0

View File

@ -107,7 +107,7 @@ if __name__ == '__main__':
rcode = yosys.run( options.design, top=options.top ) rcode = yosys.run( options.design, top=options.top )
except Exception, e: except Exception as e:
catch( e ) catch( e )
sys.exit(2) sys.exit(2)

View File

@ -209,10 +209,10 @@ class Environment ( object ):
libPath, mode = libraryEntry libPath, mode = libraryEntry
self.mbkEnv['MBK_CATA_LIB'].add( libPath, mode ) self.mbkEnv['MBK_CATA_LIB'].add( libPath, mode )
except Exception, e: except Exception as e:
e = ErrorMessage( e ) e = ErrorMessage( e )
e.addMessage( 'In %s:<Alliance> at index %d.' % (allianceFile,entryNo) ) e.addMessage( 'In %s:<Alliance> at index %d.' % (allianceFile,entryNo) )
print e print(e)
self.mbkEnv[ 'LD_LIBRARY_PATH' ] = self.mbkEnv[ 'ALLIANCE_TOP' ] + '/lib' self.mbkEnv[ 'LD_LIBRARY_PATH' ] = self.mbkEnv[ 'ALLIANCE_TOP' ] + '/lib'
return return
@ -226,7 +226,7 @@ class Environment ( object ):
env = os.environ env = os.environ
for key in self.mbkEnv.keys(): for key in self.mbkEnv.keys():
if not self.mbkEnv[key]: if not self.mbkEnv[key]:
print WarningMessage( 'Environment variable <%s> is not set.' % key ) print(WarningMessage( 'Environment variable <%s> is not set.' % key ))
continue continue
env[ key ] = str(self.mbkEnv[ key ]) env[ key ] = str(self.mbkEnv[ key ])
return env return env
@ -314,7 +314,7 @@ class ReportLog ( object ):
while True: while True:
self._reportFile = "./%s-%s-%02d.log" % (self._reportBase,timeTag,index) self._reportFile = "./%s-%s-%02d.log" % (self._reportBase,timeTag,index)
if not os.path.isfile(self._reportFile): if not os.path.isfile(self._reportFile):
print "Report log: <%s>" % self._reportFile print("Report log: <%s>" % self._reportFile)
break break
index += 1 index += 1
return return
@ -353,31 +353,31 @@ def staticInitialization ():
symbol = 'allianceConfig' symbol = 'allianceConfig'
if not os.path.isfile(confFile): if not os.path.isfile(confFile):
print '[ERROR] Missing mandatory Coriolis2 system file:' print('[ERROR] Missing mandatory Coriolis2 system file:')
print ' <%s>' % confFile print(' <%s>' % confFile)
sys.exit( 1 ) sys.exit( 1 )
try: try:
print ' o Running configuration hook: Alliance.staticInitialization().' print(' o Running configuration hook: Alliance.staticInitialization().')
print ' - Loading \"%s\".' % helpers.truncPath(confFile) print(' - Loading \"%s\".' % helpers.truncPath(confFile))
exec( open(confFile).read() ) #, moduleGlobals ) exec( open(confFile).read() ) #, moduleGlobals )
except Exception, e: except Exception as e:
print '[ERROR] An exception occured while loading the configuration file:' print('[ERROR] An exception occured while loading the configuration file:')
print ' <%s>\n' % (confFile) print(' <%s>\n' % (confFile))
print ' You should check for simple python errors in this file.' print(' You should check for simple python errors in this file.')
print ' Error was:' print(' Error was:')
print ' %s\n' % e print(' %s\n' % e)
sys.exit( 1 ) sys.exit( 1 )
if moduleGlobals.has_key(symbol): if moduleGlobals.has_key(symbol):
env.load( moduleGlobals[symbol], confFile ) env.load( moduleGlobals[symbol], confFile )
del moduleGlobals[symbol] del moduleGlobals[symbol]
else: else:
print '[ERROR] Mandatory symbol <%s> is missing in system configuration file:' % symbol print('[ERROR] Mandatory symbol <%s> is missing in system configuration file:' % symbol)
print ' <%s>' % confFile print(' <%s>' % confFile)
sys.exit( 1 ) sys.exit( 1 )
print print()
return return
@ -453,7 +453,7 @@ class Node ( EnvironmentWrapper ):
if self._dependencies == []: if self._dependencies == []:
raise ErrorMessage( 1, 'Node.setDefaultTargetName(): node is neither used nor have dependencies.' ) raise ErrorMessage( 1, 'Node.setDefaultTargetName(): node is neither used nor have dependencies.' )
self.setTarget( self.getDependency(0)._targetName+'_'+self.toolName.lower() ) self.setTarget( self.getDependency(0)._targetName+'_'+self.toolName.lower() )
print WarningMessage( 'Node.setDefaultTargetName(): Node is not affected, using: <%s>' % self.targetName ) print(WarningMessage( 'Node.setDefaultTargetName(): Node is not affected, using: <%s>' % self.targetName ))
return return
def addDependency ( self, dependency ): def addDependency ( self, dependency ):
@ -492,21 +492,21 @@ class Node ( EnvironmentWrapper ):
error = ErrorMessage( 1, 'File <%s> of node <%s> has not been created.' error = ErrorMessage( 1, 'File <%s> of node <%s> has not been created.'
% (self.fileName,self._targetName) ) % (self.fileName,self._targetName) )
if errorMessage: if errorMessage:
print print()
for line in errorMessage: print line for line in errorMessage: print(line)
if hardStop: if hardStop:
raise error raise error
else: else:
print error print(error)
return return
def isUptodate ( self ): def isUptodate ( self ):
depsMTime = 0 depsMTime = 0
#print ' Target: %-30s %d' % (self.fileName, self.mtime) #print(' Target: %-30s %d' % (self.fileName, self.mtime))
for dependency in self.getDependencies(): for dependency in self.getDependencies():
dependency.checkFile() dependency.checkFile()
depsMTime = max( depsMTime, dependency.mtime ) depsMTime = max( depsMTime, dependency.mtime )
#print ' | Dep: %-31s %d' % (dependency.fileName, dependency.mtime) #print(' | Dep: %-31s %d' % (dependency.fileName, dependency.mtime))
return depsMTime <= self.mtime return depsMTime <= self.mtime
def setActive ( self ): def setActive ( self ):
@ -522,7 +522,7 @@ class Node ( EnvironmentWrapper ):
if not isinstance(self,Source) \ if not isinstance(self,Source) \
and not isinstance(self,Probe) \ and not isinstance(self,Probe) \
and not isinstance(self,Rule): and not isinstance(self,Rule):
print 'Clean | %-30s| rm %s' % ( "<%s>"%self.ruleName, self.fileName ) print('Clean | %-30s| rm %s' % ( "<%s>"%self.ruleName, self.fileName ))
report.open() report.open()
report.write( 'Clean <%s>: (%s)\n' % (self.ruleName, self.fileName) ) report.write( 'Clean <%s>: (%s)\n' % (self.ruleName, self.fileName) )
@ -622,7 +622,7 @@ class Command ( Node ):
if self.isActive() and (not self.isUptodate() or flags & ForceRun): if self.isActive() and (not self.isUptodate() or flags & ForceRun):
if flags & ShowCommand: if flags & ShowCommand:
print "Executing | %-30s%s" % (ruleName,Command.indent(command,42)) print("Executing | %-30s%s" % (ruleName,Command.indent(command,42)))
child = subprocess.Popen( command child = subprocess.Popen( command
, env=self.env.toSystemEnv() , env=self.env.toSystemEnv()
, stdout=subprocess.PIPE , stdout=subprocess.PIPE
@ -639,7 +639,7 @@ class Command ( Node ):
if not line: break if not line: break
if flags & ShowLog: if flags & ShowLog:
print "%s" % (line[:-1]) print("%s" % (line[:-1]))
sys.stdout.flush() sys.stdout.flush()
elif flags & ShowDots: elif flags & ShowDots:
dots.dot() dots.dot()
@ -661,8 +661,8 @@ class Command ( Node ):
(pid,status) = os.waitpid(child.pid, 0) (pid,status) = os.waitpid(child.pid, 0)
status >>= 8 status >>= 8
if status != 0: if status != 0:
print print()
for line in errorLines: print line for line in errorLines: print(line)
raise ErrorMessage( 1, "%s returned status:%d." % (self.toolName,status) ) raise ErrorMessage( 1, "%s returned status:%d." % (self.toolName,status) )
if checkFile: if checkFile:
self.checkFile( hardStop=True, errorMessage=errorLines ) self.checkFile( hardStop=True, errorMessage=errorLines )
@ -670,7 +670,7 @@ class Command ( Node ):
if self.isActive(): action = 'Up to date' if self.isActive(): action = 'Up to date'
else: action = 'Inactive' else: action = 'Inactive'
if flags & ShowCommand: if flags & ShowCommand:
print "%-10s| %-30s%s" % (action,ruleName,Command.indent(command,42)) print("%-10s| %-30s%s" % (action,ruleName,Command.indent(command,42)))
report.open() report.open()
report.write( '%s command:\n' % action ) report.write( '%s command:\n' % action )
@ -1443,23 +1443,23 @@ class Tools ( object ):
if node: node.setActive() if node: node.setActive()
if commandFlags & ShowCommand and not (commandFlags & ShowLog): if commandFlags & ShowCommand and not (commandFlags & ShowLog):
print "==========+===============================+============================================" print("==========+===============================+============================================")
print " ACTION | TARGET/RULE | COMMAND" print(" ACTION | TARGET/RULE | COMMAND")
print "==========+===============================+============================================" print("==========+===============================+============================================")
if doClean: if doClean:
Node.allClean() Node.allClean()
if commandFlags & ShowCommand and not (commandFlags & ShowLog): if commandFlags & ShowCommand and not (commandFlags & ShowLog):
print "----------+-------------------------------+--------------------------------------------" print("----------+-------------------------------+--------------------------------------------")
for node in tool._staticOrder: for node in tool._staticOrder:
#for dep in node.getDependencies(): #for dep in node.getDependencies():
# print dep.name # print(dep.name)
# print dep.fileName # print(dep.fileName)
if not isinstance(node,Source) and not isinstance(node,Rule): if not isinstance(node,Source) and not isinstance(node,Rule):
if node._run(): break if node._run(): break
if commandFlags & ShowCommand and not (commandFlags & ShowLog): if commandFlags & ShowCommand and not (commandFlags & ShowLog):
print "----------+-------------------------------+--------------------------------------------" print("----------+-------------------------------+--------------------------------------------")
return return

View File

@ -219,8 +219,8 @@ def pyAlimVerticalRail ( cell, xcoord ) :
else : else :
raise ErrorMessage(2,"AlimVerticalRail : Strawberry.") raise ErrorMessage(2,"AlimVerticalRail : Strawberry.")
# print "Placement of vertical rail" # print("Placement of vertical rail")
# print "Reference ", reference # print("Reference ", reference)
power_cell = CRL.AllianceFramework.get().getCell ( "powmid_x0", CRL.Catalog.State.Views ) power_cell = CRL.AllianceFramework.get().getCell ( "powmid_x0", CRL.Catalog.State.Views )
@ -1977,16 +1977,16 @@ def affichePad ( cell ) :
global pad_north, pad_south, pad_east, pad_west global pad_north, pad_south, pad_east, pad_west
print( "Pads in the north are :" ) print( "Pads in the north are :" )
for pad in pad_north : print cell.getInstance ( pad.getName() ).getMasterCell().getName() for pad in pad_north : print(cell.getInstance ( pad.getName() ).getMasterCell().getName())
print( "Pads in the south are :" ) print( "Pads in the south are :" )
for pad in pad_south : print cell.getInstance ( pad.getName() ).getMasterCell().getName() for pad in pad_south : print(cell.getInstance ( pad.getName() ).getMasterCell().getName())
print( "Pads in the east are :" ) print( "Pads in the east are :" )
for pad in pad_east : print cell.getInstance ( pad.getName() ).getMasterCell().getName() for pad in pad_east : print(cell.getInstance ( pad.getName() ).getMasterCell().getName())
print( "Pads in the west are :" ) print( "Pads in the west are :" )
for pad in pad_west : print cell.getInstance ( pad.getName() ).getMasterCell().getName() for pad in pad_west : print(cell.getInstance ( pad.getName() ).getMasterCell().getName())
############ ############
def searchVddVss ( cell, *args ) : def searchVddVss ( cell, *args ) :
@ -2108,7 +2108,7 @@ def createGrid ( my_tuple ) :
#_Xmax = None #_Xmax = None
#_Ymax = None #_Ymax = None
coreBox = cell.getInstance('core').getAbutmentBox() coreBox = cell.getInstance('core').getAbutmentBox()
#print coreBox #print(coreBox)
_Xmin = coreBox.getXMin() _Xmin = coreBox.getXMin()
_Ymin = coreBox.getYMin() _Ymin = coreBox.getYMin()
_Xmax = coreBox.getXMax() _Xmax = coreBox.getXMax()
@ -2350,7 +2350,7 @@ def getNetInstances ( cell, net, transformation) :
_x = ins_transformation.getX ( segment.getSourceX(), segment.getSourceY() ) _x = ins_transformation.getX ( segment.getSourceX(), segment.getSourceY() )
_y = ins_transformation.getY ( segment.getSourceX(), segment.getSourceY() ) _y = ins_transformation.getY ( segment.getSourceX(), segment.getSourceY() )
#print ins, ":", segment, ",", nbSeg, ",", _x, ",", _y #print(ins, ":", segment, ",", nbSeg, ",", _x, ",", _y)
nbSeg += 1 nbSeg += 1
ck_contact_list_to_create.append ( (_x, _y) ) ck_contact_list_to_create.append ( (_x, _y) )
@ -2363,9 +2363,9 @@ def getNetInstances ( cell, net, transformation) :
Ymin = newbox.getYMin() Ymin = newbox.getYMin()
Xmax = newbox.getXMax() Xmax = newbox.getXMax()
Ymax = newbox.getYMax() Ymax = newbox.getYMax()
#print " placer contact in ", _x, " ", _y , " in the net ", plug.getMasterNet().getName() , #print(" placer contact in ", _x, " ", _y , " in the net ", plug.getMasterNet().getName())
#print " of instance ", plug.getInstance().getName() , " in ", Xmin , " ", Ymin , #print(" of instance ", plug.getInstance().getName() , " in ", Xmin , " ", Ymin)
#print " of model ", plug.getInstance().getMasterCell().getName(), "\n" #print(" of model ", plug.getInstance().getMasterCell().getName(), "\n")
# Positionner la grille # Positionner la grille
if ( Xmin < _Xmin ) or ( _Xmin == None ) : _Xmin = Xmin if ( Xmin < _Xmin ) or ( _Xmin == None ) : _Xmin = Xmin

View File

@ -333,8 +333,8 @@ class Side ( object ):
# , height # , height
# ) ) # ) )
# if not connecteds: # if not connecteds:
# print WarningMessage( 'Cannot find a suitable connector for <%s> on pad <%s>' # print(WarningMessage( 'Cannot find a suitable connector for <%s> on pad <%s>'
# % (net.getName(),pad.getName()) ) # % (net.getName(),pad.getName()) ))
# #
# trace( 550, '-' ) # trace( 550, '-' )
# return # return
@ -348,7 +348,7 @@ class Side ( object ):
# and masterCell.getName() != self._corona.pvddeckName \ # and masterCell.getName() != self._corona.pvddeckName \
# and masterCell.getName() != self._corona.pvsseckName: # and masterCell.getName() != self._corona.pvsseckName:
# continue # continue
# #print 'Power pad:', pad # #print('Power pad:', pad)
# self._createPowerContacts( pad, self._corona.vddi ) # self._createPowerContacts( pad, self._corona.vddi )
# self._createPowerContacts( pad, self._corona.vssi ) # self._createPowerContacts( pad, self._corona.vssi )
# if self._corona.useClockTree: # if self._corona.useClockTree:
@ -1281,7 +1281,7 @@ class Corona ( object ):
# if not net: # if not net:
# net = self.cell.getNet( masterNet.getName() ) # net = self.cell.getNet( masterNet.getName() )
# if not net: # if not net:
# print ErrorMessage( 1, 'Missing global net <%s> at chip level.' % masterNet.getName() ) # print(ErrorMessage( 1, 'Missing global net <%s> at chip level.' % masterNet.getName() ))
# continue # continue
# #
# for component in masterNet.getExternalComponents(): # for component in masterNet.getExternalComponents():
@ -1297,17 +1297,17 @@ class Corona ( object ):
# self._powerRails.sort( key=itemgetter(2) ) # self._powerRails.sort( key=itemgetter(2) )
# #
# #for rail in self._powerRails: # #for rail in self._powerRails:
# # print 'Pad rail %s @%d width:%d layer:%s' % ( str(rail[0].getName()) # # print('Pad rail %s @%d width:%d layer:%s' % ( str(rail[0].getName())
# # , DbU.toLambda(rail[2]) # # , DbU.toLambda(rail[2])
# # , DbU.toLambda(rail[3]) # # , DbU.toLambda(rail[3])
# # , str(rail[1].getName()) # # , str(rail[1].getName())
# # ) # # ))
# return # return
# #
# def _guessPadHvLayers ( self ): # def _guessPadHvLayers ( self ):
# if not self.powerPad: # if not self.powerPad:
# print ErrorMessage( 1, 'There must be at least one pad of model "%s" to guess the pad power terminals.' \ # print(ErrorMessage( 1, 'There must be at least one pad of model "%s" to guess the pad power terminals.' \
# % self.pvddick ) # % self.pvddick ))
# return False # return False
# #
# availableDepths = set() # availableDepths = set()
@ -1316,7 +1316,7 @@ class Corona ( object ):
# if component.getBoundingBox().getYMin() <= masterCell.getAbutmentBox().getYMin(): # if component.getBoundingBox().getYMin() <= masterCell.getAbutmentBox().getYMin():
# availableDepths.add( self.routingGauge.getLayerDepth(component.getLayer()) ) # availableDepths.add( self.routingGauge.getLayerDepth(component.getLayer()) )
# #
# #print 'available depth:', availableDepths # #print('available depth:', availableDepths)
# #
# self._horizontalPadDepth = 0 # self._horizontalPadDepth = 0
# self._verticalPadDepth = 0 # self._verticalPadDepth = 0
@ -1328,8 +1328,8 @@ class Corona ( object ):
# if self.routingGauge.getLayerGauge(depth).getDirection() == RoutingLayerGauge.Vertical: # if self.routingGauge.getLayerGauge(depth).getDirection() == RoutingLayerGauge.Vertical:
# self._verticalPadDepth = depth # self._verticalPadDepth = depth
# #
# #print 'h:', self._horizontalPadDepth # #print('h:', self._horizontalPadDepth)
# #print 'v:', self._verticalPadDepth # #print('v:', self._verticalPadDepth)
# return # return

View File

@ -587,9 +587,9 @@ def computeAbutmentBox ( cell, spaceMargin, aspectRatio, cellGauge ):
# if math.trunc(columns) != columns: columns = math.trunc(columns) + 1 # if math.trunc(columns) != columns: columns = math.trunc(columns) + 1
# else: columns = math.trunc(columns) # else: columns = math.trunc(columns)
# #
# print ' o Creating abutment box (margin:%.1f%%, aspect ratio:%.1f%%, g-length:%.1fl)' \ # print(' o Creating abutment box (margin:%.1f%%, aspect ratio:%.1f%%, g-length:%.1fl)' \
# % (spaceMargin*100.0,aspectRatio*100.0,(cellLength//sliceHeight)) # % (spaceMargin*100.0,aspectRatio*100.0,(cellLength//sliceHeight)))
# print ' - GCell grid: [%dx%d]' % (columns,rows) # print(' - GCell grid: [%dx%d]' % (columns,rows))
UpdateSession.open() UpdateSession.open()
etesian = Etesian.EtesianEngine.create( cell ) etesian = Etesian.EtesianEngine.create( cell )

View File

@ -3,20 +3,20 @@ from decimal import Decimal
techno = Techno.readFromFile("./example.dtr.xml") techno = Techno.readFromFile("./example.dtr.xml")
print "+-----------------------------+" print("+-----------------------------+")
print "| technology: "+techno.get) + " |" print("| technology: "+techno.get) + " |")
print "| units: "+techno.getUnit() +" |" print("| units: "+techno.getUnit() +" |")
print "| version: "+techno.getVersion()+" |" print("| version: "+techno.getVersion()+" |")
print "+-----------------------------+\n\n" print("+-----------------------------+\n\n")
print "transistorMinL = %s"%techno.getValue("transistorMinL") print("transistorMinL = %s"%techno.getValue("transistorMinL"))
print "transistorMinW = %s"%Decimal(techno.getValueAsString("transistorMinW")) print("transistorMinW = %s"%Decimal(techno.getValueAsString("transistorMinW")))
print "minWidth of metal1 = %s"%techno.getValue("minWidth", "metal1") print("minWidth of metal1 = %s"%techno.getValue("minWidth", "metal1"))
print "minSpacing of metal1 = %s"%techno.getValue("minWidth", "metal1") print("minSpacing of metal1 = %s"%techno.getValue("minWidth", "metal1"))
print "minSpacing of active vs poly = %s"%techno.getValue("minSpacing", "active", "poly") print("minSpacing of active vs poly = %s"%techno.getValue("minSpacing", "active", "poly"))
print "minExtension active over poly = %s"%techno.getValue("minExtension", "poly", "active") print("minExtension active over poly = %s"%techno.getValue("minExtension", "poly", "active"))
print "minArea of metal1 = %s"%techno.getValue("minArea", "metal1") print("minArea of metal1 = %s"%techno.getValue("minArea", "metal1"))
# an example of why it is important to use Decimal in python: # an example of why it is important to use Decimal in python:
print techno.getValue("minArea", "metal1")*3-0.3 # returns 5.55111512313e-17 print(techno.getValue("minArea", "metal1")*3-0.3) # returns 5.55111512313e-17
print Decimal(techno.getValueAsString("minArea", "metal1"))*3-Decimal('0.3') # returns 0.000 print(Decimal(techno.getValueAsString("minArea", "metal1"))*3-Decimal('0.3')) # returns 0.000

View File

@ -4,20 +4,20 @@ library = Library.readFromFile("./testParse.lib")
if ( library ) : if ( library ) :
# print of the library # print of the library
print library print(library)
# print of one attribute in particular of a cell # print of one attribute in particular of a cell
print "Area of inv_x1 :", library.getCell("inv_x1").getAttribute("area").valueAsString() print("Area of inv_x1 :", library.getCell("inv_x1").getAttribute("area").valueAsString())
print "Timing intrinsic_rise of nq of inv_x1 :", library.getCell("inv_x1").getPin("nq").getTiming("i").getAttribute("intrinsic_rise").valueAsString() print("Timing intrinsic_rise of nq of inv_x1 :", library.getCell("inv_x1").getPin("nq").getTiming("i").getAttribute("intrinsic_rise").valueAsString())
# print of all the attributes of a cell # print of all the attributes of a cell
print "Attributes of no2_x1 :" print("Attributes of no2_x1 :")
for attr in library.getCell("no2_x1").getAttributes() : for attr in library.getCell("no2_x1").getAttributes() :
print " name=", attr.key, \ print(" name=", attr.key,
", type=", attr.value.typeToString(), \ ", type=", attr.value.typeToString(),
", value=", attr.value.valueAsString() ", value=", attr.value.valueAsString())
# print of all the timings of a pin # print of all the timings of a pin
print "Timing's attributes of pin nq of no2_x1 :" print("Timing's attributes of pin nq of no2_x1 :")
for timing in library.getCell("no2_x1").getPin("nq").getTimings() : for timing in library.getCell("no2_x1").getPin("nq").getTimings() :
print timing print(timing)
else : else :
raise ( "library is NULL" ) raise ( "library is NULL" )

View File

@ -3,104 +3,104 @@ import sys
from SPICE import * from SPICE import *
def printContents(circuit): def printContents(circuit):
print "+", circuit.title print("+", circuit.title)
if len(circuit.getIncludes()): if len(circuit.getIncludes()):
print "| + includes" print("| + includes")
for include in circuit.getIncludes(): for include in circuit.getIncludes():
print "| |", include print("| |", include)
if len(circuit.getLibraries()): if len(circuit.getLibraries()):
print "| + libraries" print("| + libraries")
for (lib, typ) in circuit.getLibraries(): for (lib, typ) in circuit.getLibraries():
print "| |", lib, typ print("| |", lib, typ)
if len(circuit.getParameters()): if len(circuit.getParameters()):
print "| + parameters" print("| + parameters")
for (name, value) in circuit.getParameters().items(): for (name, value) in circuit.getParameters().items():
print "| | %s=%s"%(name, value) print("| | %s=%s"%(name, value))
if len(circuit.getOptions()): if len(circuit.getOptions()):
print "| + options" print("| + options")
for (name, value) in circuit.getOptions().items(): for (name, value) in circuit.getOptions().items():
print "| | %s=%s"%(name, value) print("| | %s=%s"%(name, value))
if len(circuit.getSources()): if len(circuit.getSources()):
print "| + sources" print("| + sources")
for source in circuit.getSources(): for source in circuit.getSources():
print "| |", source.getName(), source.getPositive(), source.getNegative(), source.getValue() print("| |", source.getName(), source.getPositive(), source.getNegative(), source.getValue())
if len(circuit.getSubckts()): if len(circuit.getSubckts()):
print "| + subckts" print("| + subckts")
for sub in circuit.getSubckts(): for sub in circuit.getSubckts():
print "| | +", sub.getName(), print("| | +", sub.getName())
for interf in sub.getInterfaces(): for interf in sub.getInterfaces():
print interf, print(interf)
if len(sub.getParameters()): if len(sub.getParameters()):
print "param:", print("param:")
for (name, value) in sub.getParameters().items(): for (name, value) in sub.getParameters().items():
print "%s=%s"%(name,value), print("%s=%s"%(name,value))
print print()
for inst in sub.getInstances(): for inst in sub.getInstances():
print "| | | +", inst.getName(), print("| | | +", inst.getName())
if isinstance(inst, Mosfet): if isinstance(inst, Mosfet):
print inst.getDrain(), inst.getGrid(), inst.getSource(), inst.getBulk(), inst.getModel(), print(inst.getDrain(), inst.getGrid(), inst.getSource(), inst.getBulk(), inst.getModel())
i = 0 i = 0
for (name, value) in inst.getParameters().items(): for (name, value) in inst.getParameters().items():
if i%6 == 0: if i%6 == 0:
print print()
print "| | | | +", print("| | | | +")
print "%s=%s"%(name, value), print("%s=%s"%(name, value))
i += 1 i += 1
elif isinstance(inst, Resistor): elif isinstance(inst, Resistor):
print inst.getFirst(), inst.getSecond(), inst.getValue(), print(inst.getFirst(), inst.getSecond(), inst.getValue())
elif isinstance(inst, Capacitor): elif isinstance(inst, Capacitor):
print inst.getPositive(), inst.getNegative(), inst.getValue(), print(inst.getPositive(), inst.getNegative(), inst.getValue())
else: else:
for conn in inst.getConnectors(): for conn in inst.getConnectors():
print conn, print(conn)
print inst.getModel(), print(inst.getModel())
i = 0 i = 0
for (name, value) in inst.getParameters().items(): for (name, value) in inst.getParameters().items():
if i%6 == 0: if i%6 == 0:
print print()
print "| | | | +", print("| | | | +")
print "%s=%s"%(name, value), print("%s=%s"%(name, value))
i += 1 i += 1
print print()
if len(circuit.getInstances()): if len(circuit.getInstances()):
print "| + instances" print("| + instances")
for inst in circuit.getInstances(): for inst in circuit.getInstances():
print "| | | +", inst.getName(), print("| | | +", inst.getName())
if isinstance(inst, Mosfet): if isinstance(inst, Mosfet):
print inst.getDrain(), inst.getGrid(), inst.getSource(), inst.getBulk(), inst.getModel(), print(inst.getDrain(), inst.getGrid(), inst.getSource(), inst.getBulk(), inst.getModel())
i = 0 i = 0
for (name, value) in inst.getParameters().items(): for (name, value) in inst.getParameters().items():
if i%6 == 0: if i%6 == 0:
print print()
print "| | | | +", print("| | | | +")
print "%s=%s"%(name, value), print("%s=%s"%(name, value))
i += 1 i += 1
elif isinstance(inst, Resistor): elif isinstance(inst, Resistor):
print inst.getFirst(), inst.getSecond(), inst.getValue(), print(inst.getFirst(), inst.getSecond(), inst.getValue())
elif isinstance(inst, Capacitor): elif isinstance(inst, Capacitor):
print inst.getPositive(), inst.getNegative(), inst.getValue(), print(inst.getPositive(), inst.getNegative(), inst.getValue())
else: else:
for conn in inst.getConnectors(): for conn in inst.getConnectors():
print conn, print(conn)
print inst.getModel(), print(inst.getModel())
i = 0 i = 0
for (name, value) in inst.getParameters().items(): for (name, value) in inst.getParameters().items():
if i%6 == 0: if i%6 == 0:
print print()
print "| | | | +", print("| | | | +")
print "%s=%s"%(name, value), print("%s=%s"%(name, value))
i += 1 i += 1
print print()
def usage(): def usage():
print "usage:", sys.argv[0], "[filename]" print("usage:", sys.argv[0], "[filename]")
sys.exit(48) sys.exit(48)
def main(): def main():

View File

@ -23,23 +23,23 @@ try:
import plugins.ClockTreePlugin import plugins.ClockTreePlugin
import plugins.ChipPlace import plugins.ChipPlace
import plugins.RSavePlugin import plugins.RSavePlugin
except ImportError, e: except ImportError as e:
serror = str(e) serror = str(e)
if serror.startswith('No module named'): if serror.startswith('No module named'):
module = serror.split()[-1] module = serror.split()[-1]
print '[ERROR] The <%s> python module or symbol cannot be loaded.' % module print('[ERROR] The <%s> python module or symbol cannot be loaded.' % module)
print ' Please check the integrity of the <coriolis> package.' print(' Please check the integrity of the <coriolis> package.')
sys.exit(1) sys.exit(1)
if str(e).find('cannot open shared object file'): if str(e).find('cannot open shared object file'):
library = serror.split(':')[0] library = serror.split(':')[0]
print '[ERROR] The <%s> shared library cannot be loaded.' % library print('[ERROR] The <%s> shared library cannot be loaded.' % library)
print ' Under RHEL 6, you must be under devtoolset-2.' print(' Under RHEL 6, you must be under devtoolset-2.')
print ' (scl enable devtoolset-2 bash)' print(' (scl enable devtoolset-2 bash)')
sys.exit(1) sys.exit(1)
except Exception, e: except Exception as e:
print '[ERROR] A strange exception occurred while loading the basic Coriolis/Python' print('[ERROR] A strange exception occurred while loading the basic Coriolis/Python')
print ' modules. Something may be wrong at Python/C API level.\n' print(' modules. Something may be wrong at Python/C API level.\n')
print ' %s' % e print(' %s' % e)
sys.exit(2) sys.exit(2)
@ -97,8 +97,8 @@ def scriptMain ( **kw ):
plugins.RSavePlugin.scriptMain( **kw ) plugins.RSavePlugin.scriptMain( **kw )
except Exception, e: except Exception as e:
print helpers.io.catch( e ) print(helpers.io.catch( e ))
return success return success
@ -129,23 +129,23 @@ if __name__ == '__main__':
try: try:
module = __import__( options.script, globals(), locals() ) module = __import__( options.script, globals(), locals() )
if not module.__dict__.has_key('scriptMain'): if not module.__dict__.has_key('scriptMain'):
print '[ERROR] Script module <%s> do not contains a ScripMain() function.' % options.script print('[ERROR] Script module <%s> do not contains a ScripMain() function.' % options.script)
sys.exit(1) sys.exit(1)
cell = module.__dict__['scriptMain']( **kw ) cell = module.__dict__['scriptMain']( **kw )
kw['cell'] = cell kw['cell'] = cell
except ImportError, e: except ImportError as e:
module = str(e).split()[-1] module = str(e).split()[-1]
print '[ERROR] The <%s> script cannot be loaded.' % module print('[ERROR] The <%s> script cannot be loaded.' % module)
print ' Please check your design hierarchy.' print(' Please check your design hierarchy.')
sys.exit(1) sys.exit(1)
except Exception, e: except Exception as e:
print '[ERROR] A strange exception occurred while loading the Python' print('[ERROR] A strange exception occurred while loading the Python')
print ' script <%s>. Please check that module for error:\n' % options.script print(' script <%s>. Please check that module for error:\n' % options.script)
traceback.print_tb(sys.exc_info()[2]) traceback.print_tb(sys.exc_info()[2])
print ' %s' % e print(' %s' % e)
sys.exit(2) sys.exit(2)
elif options.cell: elif options.cell:
kw['cell'] = framework.getCell( options.cell, CRL.Catalog.State.Views ) kw['cell'] = framework.getCell( options.cell, CRL.Catalog.State.Views )

View File

@ -98,8 +98,8 @@ class VerticalRoutingTracks ( CapacitorStack ):
self.setRules () self.setRules ()
vRoutingTracksLayer = DataBase.getDB().getTechnology().getLayer("metal3" ) vRoutingTracksLayer = DataBase.getDB().getTechnology().getLayer("metal3" )
#print 'self.capacitorInstance.doMatrix:', self.capacitorInstance.doMatrix #print('self.capacitorInstance.doMatrix:', self.capacitorInstance.doMatrix)
#print 'self.capacitorsNumber:', self.capacitorsNumber #print('self.capacitorsNumber:', self.capacitorsNumber)
if self.capacitorInstance.doMatrix == True and self.capacitorsNumber > 1 : if self.capacitorInstance.doMatrix == True and self.capacitorsNumber > 1 :
self.minimizeVRTs() self.minimizeVRTs()

View File

@ -52,16 +52,16 @@ def checkCoherency ( device, bbMode ):
columns = pmatrix.getColumns() columns = pmatrix.getColumns()
for row in range(rows): for row in range(rows):
#print ' [', #print(' [')
for column in range(columns): for column in range(columns):
capaIndex = pmatrix.getValue(row,column) capaIndex = pmatrix.getValue(row,column)
#print '%2d' % capaIndex, #print('%2d' % capaIndex)
if capaIndex >= capacities.getCount(): if capaIndex >= capacities.getCount():
valid = False valid = False
message += ' element [%d,%d] == %d is out of range, must be in [0..%d]\n' \ message += ' element [%d,%d] == %d is out of range, must be in [0..%d]\n' \
% (row,column,capaIndex,capacities.getCount()-1) % (row,column,capaIndex,capacities.getCount()-1)
#print ']' #print(']')
if not valid: return (False, message) if not valid: return (False, message)

View File

@ -52,7 +52,7 @@ class Pathes ( object ):
def __init__ ( self, name ): def __init__ ( self, name ):
self.name = name self.name = name
self.components = [] self.components = []
if os.environ.has_key(name): if name in os.environ:
self.components = os.environ[name].split(':') self.components = os.environ[name].split(':')
return return
@ -72,9 +72,9 @@ class Pathes ( object ):
return return
def show ( self ): def show ( self ):
print ' %s:' % self.name print(' %s:' % self.name)
for component in self.components: for component in self.components:
print ' %s' % component print(' %s' % component)
return return
@ -86,38 +86,38 @@ if arch == 'x86_64' and os.path.exists('/usr/lib64'): libDir = '/lib64'
pythonSitePackages = os.path.join( *(distutils.sysconfig.get_python_lib(1).split('/')[-3:]) ) pythonSitePackages = os.path.join( *(distutils.sysconfig.get_python_lib(1).split('/')[-3:]) )
print ' ========================================' print(' ========================================')
print ' OS:\n %s' % osType print(' OS:\n %s' % osType)
scriptBinPath = os.path.abspath(os.path.dirname(sys.argv[0])) scriptBinPath = os.path.abspath(os.path.dirname(sys.argv[0]))
print ' Script location:\n %s' % scriptBinPath print(' Script location:\n %s' % scriptBinPath)
if scriptBinPath == '/usr/bin': if scriptBinPath == '/usr/bin':
location = Location.BaseSystem location = Location.BaseSystem
coriolisTop = '/usr' coriolisTop = '/usr'
print ' Using standard system installation scheme.' print(' Using standard system installation scheme.')
elif scriptBinPath == '/soc/coriolis2/bin': elif scriptBinPath == '/soc/coriolis2/bin':
location = Location.Devtoolset2 location = Location.Devtoolset2
coriolisTop = '/soc/coriolis2' coriolisTop = '/soc/coriolis2'
print ' Using RHEL6 installation scheme.' print(' Using RHEL6 installation scheme.')
ldLibraryPath = os.getenv('LD_LIBRARY_PATH') ldLibraryPath = os.getenv('LD_LIBRARY_PATH')
if not 'devtoolset' in ldLibraryPath: if not 'devtoolset' in ldLibraryPath:
print '[ERROR] You must enable the devtoolset-2 before running Coriolis:' print('[ERROR] You must enable the devtoolset-2 before running Coriolis:')
print ' > scl enable devtoolset-2 bash' print(' > scl enable devtoolset-2 bash')
sys.exit( 1 ) sys.exit( 1 )
else: else:
location = Location.UserDefined location = Location.UserDefined
coriolisTop = truncPath( scriptBinPath, 0, -1 ) coriolisTop = truncPath( scriptBinPath, 0, -1 )
print ' Using User installation scheme.' print(' Using User installation scheme.')
if location & Location.SetCoriolisTop: if location & Location.SetCoriolisTop:
os.environ['CORIOLIS_TOP'] = coriolisTop os.environ['CORIOLIS_TOP'] = coriolisTop
print ' CORIOLIS_TOP:\n %s' % coriolisTop print(' CORIOLIS_TOP:\n %s' % coriolisTop)
if location & Location.BaseSysconfDir: if location & Location.BaseSysconfDir:
sysConfDir = truncPath( coriolisTop, 0, -1 ) + '/etc/coriolis2' sysConfDir = truncPath( coriolisTop, 0, -1 ) + '/etc/coriolis2'
else: else:
sysConfDir = coriolisTop + '/etc/coriolis2' sysConfDir = coriolisTop + '/etc/coriolis2'
print ' Configuration directory:\n %s' % sysConfDir print(' Configuration directory:\n %s' % sysConfDir)
os.environ['STRATUS_MAPPING_NAME'] = sysConfDir+'/stratus2sxlib.xml' os.environ['STRATUS_MAPPING_NAME'] = sysConfDir+'/stratus2sxlib.xml'
@ -153,14 +153,14 @@ if len(sys.argv) > 1 and sys.argv[1].startswith('--run='):
argvStart = 1 argvStart = 1
slaveScript = sys.argv[1][6:] slaveScript = sys.argv[1][6:]
print ' Script:\n %s' % slaveScript print(' Script:\n %s' % slaveScript)
print ' ========================================' print(' ========================================')
try: try:
os.execvp( slaveScript, sys.argv[argvStart:] ) os.execvp( slaveScript, sys.argv[argvStart:] )
except Exception, e: except Exception as e:
print '[ERROR] An exception occured while lauching <%s>\n' % slaveScript print('[ERROR] An exception occured while lauching <%s>\n' % slaveScript)
print e print(e)
sys.exit( 3 ) sys.exit( 3 )
sys.exit( 0 ) sys.exit( 0 )