Prepare py3 port and display sys.argv on internal errors.

This commit is contained in:
Bastian Kleineidam 2012-11-26 18:49:07 +01:00
parent 8fbcd31798
commit 42a17cbb98
29 changed files with 139 additions and 124 deletions

View file

@ -211,11 +211,11 @@ sign_distfiles:
done
test: localbuild
env LANG=C $(PYTHON) -m pytest $(PYTESTOPTS) $(TESTOPTS) $(TESTS)
env LANG=en_US.utf-8 $(PYTHON) -m pytest $(PYTESTOPTS) $(TESTOPTS) $(TESTS)
pyflakes:
pyflakes $(PY_FILES_DIRS) 2>&1 | \
grep -v -E "redefinition of unused '(StringIO|Editor|ContentTypeLexers)'" | \
grep -v -E "redefinition of unused '(StringIO|Editor|ContentTypeLexers|winreg)'" | \
grep -v "local variable 'dummy' is assigned to but never used" | \
grep -v -E "'(py2exe|py2app|PyQt4|biplist|setuptools|win32com|find_executable|parse_bookmark_data|parse_bookmark_file|wsgiref|pyftpdlib|linkchecker_rc)' imported but unused" | \
grep -v -E "redefinition of unused '(setup|Distribution|build)'" | \

View file

@ -1,5 +1,8 @@
8.3 "" (released xx.xx.xxxx)
Changes:
- logging: Print system arguments (sys.argv) in internal error information.
8.2 "Belle De Jour" (released 9.11.2012)

View file

@ -44,7 +44,7 @@ class CookieJar (object):
self.cache.remove(cookie)
if not cookie.is_expired():
self.cache.add(cookie)
except cookies.CookieError, msg:
except cookies.CookieError as msg:
errmsg = "Invalid cookie %r for %s:%s%s: %s" % (
h, scheme, host, path, msg)
errors.append(errmsg)
@ -56,7 +56,7 @@ class CookieJar (object):
self.cache.remove(cookie)
if not cookie.is_expired():
self.cache.add(cookie)
except cookies.CookieError, msg:
except cookies.CookieError as msg:
errmsg = "Invalid cookie2 %r for %s:%s%s: %s" % (
h, scheme, host, path, msg)
errors.append(errmsg)

View file

@ -114,7 +114,7 @@ class FileUrl (urlbase.UrlBase):
if not is_absolute_path(base_url):
try:
base_url = os.getcwd()+"/"+base_url
except OSError, msg:
except OSError as msg:
# occurs on stale remote filesystems (eg. NFS)
errmsg = _("Could not get current working directory: %(msg)s") % dict(msg=msg)
raise LinkCheckerError(errmsg)

View file

@ -94,7 +94,7 @@ class FtpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledco
log.debug(LOG_CHECK, "FTP info %s", info)
else:
raise LinkCheckerError(_("Got no answer from FTP server"))
except EOFError, msg:
except EOFError as msg:
raise LinkCheckerError(
_("Remote host has closed connection: %(msg)s") % str(msg))
@ -103,7 +103,7 @@ class FtpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledco
See also RFC 2640."""
try:
features = self.url_connection.sendcmd("FEAT")
except ftplib.error_perm, msg:
except ftplib.error_perm as msg:
log.debug(LOG_CHECK, "Ignoring error when getting FTP features: %s" % msg)
else:
log.debug(LOG_CHECK, "FTP features %s", features)

View file

@ -72,7 +72,7 @@ class HttpsUrl (httpurl.HttpUrl):
"""
try:
match_hostname(cert, host)
except CertificateError, msg:
except CertificateError as msg:
self.add_ssl_warning(ssl_sock, msg)
def check_ssl_valid_date(self, ssl_sock, cert):
@ -83,7 +83,7 @@ class HttpsUrl (httpurl.HttpUrl):
checkDaysValid = self.aggregate.config["warnsslcertdaysvalid"]
try:
notAfter = ssl.cert_time_to_seconds(cert['notAfter'])
except ValueError, msg:
except ValueError as msg:
msg = _('invalid certficate "notAfter" value %r') % cert['notAfter']
self.add_ssl_warning(ssl_sock, msg)
return

View file

@ -166,14 +166,14 @@ class HttpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledc
self.close_response()
try:
self._try_http_response()
except httplib.BadStatusLine, msg:
except httplib.BadStatusLine as msg:
# some servers send empty HEAD replies
if self.method == "HEAD" and self.method_get_allowed:
log.debug(LOG_CHECK, "Bad status line %r: falling back to GET", msg)
self.fallback_to_get()
continue
raise
except socket.error, msg:
except socket.error as msg:
# some servers reset the connection on HEAD requests
if self.method == "HEAD" and self.method_get_allowed and \
msg[0] == errno.ECONNRESET:
@ -207,7 +207,7 @@ class HttpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledc
self.proxy, self.proxyauth = oldproxy
try:
tries = self.follow_redirections()
except httplib.BadStatusLine, msg:
except httplib.BadStatusLine as msg:
# some servers send empty HEAD replies
if self.method == "HEAD" and self.method_get_allowed:
log.debug(LOG_CHECK, "Bad status line %r: falling back to GET", msg)
@ -493,7 +493,7 @@ class HttpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledc
"""
try:
self._get_http_response()
except socket.error, msg:
except socket.error as msg:
if msg.args[0] == 32 and self.persistent:
# server closed persistent connection - retry
log.debug(LOG_CHECK, "Server closed connection: retry")
@ -501,7 +501,7 @@ class HttpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledc
self._get_http_response()
else:
raise
except httplib.BadStatusLine, msg:
except httplib.BadStatusLine as msg:
if self.persistent:
# server closed connection - retry
log.debug(LOG_CHECK, "Empty status line: retry")
@ -690,7 +690,7 @@ class HttpUrl (internpaturl.InternPatternUrl, proxysupport.ProxySupport, pooledc
f = StringIO(zlib.decompress(data))
else:
f = gzip.GzipFile('', 'rb', 9, StringIO(data))
except zlib.error, msg:
except zlib.error as msg:
log.debug(LOG_CHECK, "Error %s data of len %d", encoding, len(data))
self.add_warning(_("Decompress error %(err)s") %
{"err": str(msg)},

View file

@ -122,7 +122,7 @@ class MailtoUrl (urlbase.UrlBase):
if key.lower() in EMAIL_CGI:
# Only the first header value is added
self.addresses.update(getaddresses(urllib.unquote(vals[0])))
except ValueError, err:
except ValueError as err:
self.add_warning(_("Error parsing CGI values: %s") % str(err))
else:
self.addresses.update(getaddresses(url))
@ -330,7 +330,7 @@ class MailtoUrl (urlbase.UrlBase):
else:
self.add_warning(_("Unverified address: %(info)s.") % d,
tag=WARN_MAIL_UNVERIFIED_ADDRESS)
except smtplib.SMTPException, msg:
except smtplib.SMTPException as msg:
self.add_warning(
_("MX mail host %(host)s did not accept connections: "
"%(error)s.") % {'host': host, 'error': str(msg)},

View file

@ -79,7 +79,7 @@ class NntpUrl (urlbase.UrlBase):
nntp = nntplib.NNTP(nntpserver, usenetrc=False)
except nntplib.NNTPTemporaryError:
self.wait()
except nntplib.NNTPPermanentError, msg:
except nntplib.NNTPPermanentError as msg:
if re.compile("^50[45]").search(str(msg)):
self.wait()
else:

View file

@ -263,7 +263,7 @@ class UrlBase (object):
try:
parser.feed(self.get_content())
parser.flush()
except linkparse.StopParse, msg:
except linkparse.StopParse as msg:
log.debug(LOG_CHECK, "Stopped parsing: %s", msg)
# break cyclic dependencies
handler.parser = None
@ -393,7 +393,7 @@ class UrlBase (object):
try:
self.build_url()
self.check_url_warnings()
except tuple(ExcSyntaxList), msg:
except tuple(ExcSyntaxList) as msg:
self.set_result(unicode_safe(msg), valid=False)
else:
self.set_cache_keys()
@ -640,7 +640,7 @@ class UrlBase (object):
try:
parser.feed(self.get_content())
parser.flush()
except linkparse.StopParse, msg:
except linkparse.StopParse as msg:
log.debug(LOG_CHECK, "Stopped parsing: %s", msg)
# break cyclic dependencies
handler.parser = None
@ -667,7 +667,7 @@ class UrlBase (object):
try:
parser.feed(self.get_content())
parser.flush()
except linkparse.StopParse, msg:
except linkparse.StopParse as msg:
log.debug(LOG_CHECK, "Stopped parsing: %s", msg)
# break cyclic dependencies
handler.parser = None

View file

@ -17,6 +17,7 @@
"""
Utility functions suitable for command line clients.
"""
from __future__ import print_function
import sys
import optparse
from . import fileutil, ansicolor, strformat, checker
@ -32,8 +33,8 @@ def print_version(exit_code=0):
def print_usage (msg, exit_code=2):
"""Print a program msg text to stderr and exit."""
program = sys.argv[0]
print >> console.stderr, _("Error: %(msg)s") % {"msg": msg}
print >> console.stderr, _("Execute '%(program)s -h' for help") % {"program": program}
print(_("Error: %(msg)s") % {"msg": msg}, file=console.stderr)
print(_("Execute '%(program)s -h' for help") % {"program": program}, file=console.stderr)
sys.exit(exit_code)
@ -105,7 +106,7 @@ class LCOptionParser (optparse.OptionParser, object):
if fileutil.is_tty(out):
strformat.paginate(s)
else:
print >>out, s
print(s, file=out)
sys.exit(0)
@notimplemented

View file

@ -473,7 +473,7 @@ def get_user_config():
userdir += "."
os.mkdir(userdir, 0700)
shutil.copy(initialconf, userconf)
except StandardError, errmsg:
except StandardError as errmsg:
msg = _("could not copy initial configuration file %(src)r to %(dst)r: %(errmsg)r")
args = dict(src=initialconf, dst=userconf, errmsg=errmsg)
log.warn(LOG_CHECK, msg % args)
@ -495,7 +495,7 @@ def get_gconf_http_proxy ():
if not port:
port = 8080
return "%s:%d" % (host, port)
except StandardError, msg:
except StandardError as msg:
log.debug(LOG_CHECK, "error getting HTTP proxy from gconf: %s", msg)
return None
@ -514,7 +514,7 @@ def get_gconf_ftp_proxy ():
if not port:
port = 8080
return "%s:%d" % (host, port)
except StandardError, msg:
except StandardError as msg:
log.debug(LOG_CHECK, "error getting FTP proxy from gconf: %s", msg)
return None
@ -528,7 +528,7 @@ def get_kde_http_proxy ():
try:
data = read_kioslaverc(config_dir)
return data.get("http_proxy")
except StandardError, msg:
except StandardError as msg:
log.debug(LOG_CHECK, "error getting HTTP proxy from KDE: %s", msg)
@ -541,7 +541,7 @@ def get_kde_ftp_proxy ():
try:
data = read_kioslaverc(config_dir)
return data.get("ftp_proxy")
except StandardError, msg:
except StandardError as msg:
log.debug(LOG_CHECK, "error getting FTP proxy from KDE: %s", msg)
# The following KDE functions are largely ported and ajusted from

View file

@ -57,7 +57,7 @@ class LCConfigParser (ConfigParser.RawConfigParser, object):
self.read_checking_config()
self.read_authentication_config()
self.read_filtering_config()
except Exception, msg:
except Exception as msg:
raise LinkCheckerError(
_("Error parsing configuration: %s") % unicode(msg))
@ -92,7 +92,7 @@ class LCConfigParser (ConfigParser.RawConfigParser, object):
"""Read configuration options in section "output"."""
section = "output"
from ..logger import Loggers
for key in Loggers.iterkeys():
for key in Loggers.keys():
if self.has_section(key):
for opt in self.options(key):
self.config[key][opt] = self.get(key, opt)

View file

@ -206,7 +206,7 @@ class LFUCache (dict):
"""Shrink ca. 5% of entries."""
trim = int(0.05*len(self))
if trim:
items = super(LFUCache, self).iteritems()
items = super(LFUCache, self).items()
# sorting function for items
keyfunc = lambda x: x[1][0]
values = sorted(items, key=keyfunc)
@ -244,7 +244,7 @@ class LFUCache (dict):
def iteritems (self):
"""Return iterator of items, not updating usage count."""
for key, value in super(LFUCache, self).iteritems():
for key, value in super(LFUCache, self).items():
yield (key, value[1])
def values (self):
@ -253,7 +253,7 @@ class LFUCache (dict):
def itervalues (self):
"""Return iterator of values, not updating usage count."""
for value in super(LFUCache, self).itervalues():
for value in super(LFUCache, self).values():
yield value[1]
def popitem (self):

View file

@ -22,7 +22,7 @@ Example:
@synchronized(thread.allocate_lock())
def f ():
"Synchronized function"
print "i am synchronized:", f, f.__doc__
print("i am synchronized:", f, f.__doc__)
@deprecated
def g ():
@ -35,6 +35,7 @@ def h ():
pass
"""
from __future__ import print_function
import warnings
import signal
import os
@ -95,7 +96,7 @@ def synchronize (lock, func, log_duration_secs=0):
with lock:
duration = time.time() - t
if duration > log_duration_secs > 0:
print >> sys.stderr, "WARN:", func.__name__, "locking took %0.2f seconds" % duration
print("WARN:", func.__name__, "locking took %0.2f seconds" % duration, file=sys.stderr)
return func(*args, **kwargs)
return update_func_meta(newfunc, func)
@ -124,9 +125,9 @@ def timeit (func, log, limit):
res = func(*args, **kwargs)
duration = time.time() - t
if duration > limit:
print >> log, func.__name__, "took %0.2f seconds" % duration
print >> log, args
print >> log, kwargs
print(func.__name__, "took %0.2f seconds" % duration, file=log)
print(args, file=log)
print(kwargs, file=log)
return res
return update_func_meta(newfunc, func)

View file

@ -126,7 +126,7 @@ def check_urls (aggregate):
"""
try:
visit_loginurl(aggregate)
except Exception, msg:
except Exception as msg:
log.warn(LOG_CHECK, _("Error using login URL: %(msg)s.") % \
{'msg': str(msg)})
raise

View file

@ -17,6 +17,7 @@
"""
Helpers for console output.
"""
from __future__ import print_function
import sys
import os
import time
@ -70,8 +71,8 @@ class StatusLogger (object):
def internal_error (out=stderr, etype=None, evalue=None, tb=None):
"""Print internal error message (output defaults to stderr)."""
print >> out, os.linesep
print >> out, _("""********** Oops, I did it again. *************
print(os.linesep, file=out)
print(_("""********** Oops, I did it again. *************
You have found an internal error in LinkChecker. Please write a bug report
at %s
@ -86,27 +87,27 @@ When using the commandline client:
Not disclosing some of the information above due to privacy reasons is ok.
I will try to help you nonetheless, but you have to give me something
I can work with ;) .
""") % configuration.SupportUrl
""") % configuration.SupportUrl, file=out)
if etype is None:
etype = sys.exc_info()[0]
if evalue is None:
evalue = sys.exc_info()[1]
print >> out, etype, evalue
print(etype, evalue, file=out)
if tb is None:
tb = sys.exc_info()[2]
traceback.print_exception(etype, evalue, tb, None, out)
print_app_info(out=out)
print_proxy_info(out=out)
print_locale_info(out=out)
print >> out, os.linesep, \
_("******** LinkChecker internal error, over and out ********")
print(os.linesep,
_("******** LinkChecker internal error, over and out ********"), file=out)
def print_env_info (key, out=stderr):
"""If given environment key is defined, print it out."""
value = os.getenv(key)
if value is not None:
print >> out, key, "=", repr(value)
print(key, "=", repr(value), file=out)
def print_proxy_info (out=stderr):
@ -119,7 +120,7 @@ def print_locale_info (out=stderr):
"""Print locale info."""
for key in ("LANGUAGE", "LC_ALL", "LC_CTYPE", "LANG"):
print_env_info(key, out=out)
print >> out, _("Default locale:"), i18n.get_locale()
print(_("Default locale:"), i18n.get_locale(), file=out)
# Environment variables influencing the interpreter execution
# See python(1) man page.
@ -141,18 +142,19 @@ PYTHON_ENV_VARS = (
)
def print_app_info (out=stderr):
"""Print system and application info (output defaults to stderr)."""
print >> out, _("System info:")
print >> out, configuration.App
print >> out, _("Python %(version)s on %(platform)s") % \
{"version": sys.version, "platform": sys.platform}
print(_("System info:"), file=out)
print(configuration.App, file=out)
print(_("Python %(version)s on %(platform)s") %
{"version": sys.version, "platform": sys.platform}, file=out)
for key in PYTHON_ENV_VARS:
print_env_info(key, out=out)
for line in configuration.get_modules_info():
print >> out, line
print(line, file=out)
stime = strformat.strtime(time.time())
print >> out, _("Local time:"), stime
print(_("Local time:"), stime, file=out)
print(_("sys.argv:"), sys.argv, file=out)
def print_version (out=stdout):
"""Print the program version (output defaults to stdout)."""
print >> out, configuration.AppInfo
print(configuration.AppInfo, file=out)

View file

@ -25,6 +25,7 @@ import stat
import fnmatch
import mimetypes
import tempfile
import importlib
from distutils.spawn import find_executable
from .decorators import memoized
@ -65,7 +66,7 @@ def has_module (name):
@rtype: bool
"""
try:
exec "import %s" % name
importlib.import_module(name)
return True
except (OSError, ImportError):
# some modules (for example HTMLtidy) raise OSError
@ -196,7 +197,7 @@ def init_mimedb():
global mimedb
try:
mimedb = mimetypes.MimeTypes(strict=False)
except StandardError, msg:
except StandardError as msg:
log.error(LOG_CHECK, "could not initialize MIME database: %s" % msg)
return
# For Opera bookmark files (opera6.adr)

View file

@ -234,7 +234,7 @@ class LinkCheckerMain (QtGui.QMainWindow, Ui_MainWindow):
"""Read user and system configuration file."""
try:
self.config.read()
except LinkCheckerError, msg:
except LinkCheckerError as msg:
self.config_error = unicode(msg)
def set_config (self):

View file

@ -136,7 +136,7 @@ class EditorWindow (QtGui.QDialog, Ui_EditorDialog):
stream << self.editor.text()
self.editor.setModified(False)
saved = True
except (IOError, OSError), e:
except (IOError, OSError) as e:
err = QtGui.QMessageBox(self)
err.setText(str(e))
err.exec_()
@ -170,7 +170,7 @@ class EditorWindow (QtGui.QDialog, Ui_EditorDialog):
stream.setCodec("UTF-8")
self.setText(stream.readAll())
loaded = True
except (IOError, OSError), e:
except (IOError, OSError) as e:
err = QtGui.QMessageBox(self)
err.setText(str(e))
err.exec_()

View file

@ -114,7 +114,7 @@ def saveproject(parent, url):
"""Save a project file."""
try:
msg = saveproject_msg(parent, url)
except StandardError, errmsg:
except StandardError as errmsg:
msg = str(errmsg)
parent.set_statusmsg(msg)
@ -168,7 +168,7 @@ def openproject (parent):
"""Select and load a project file."""
try:
msg = openproject_msg(parent)
except StandardError, errmsg:
except StandardError as errmsg:
msg = str(errmsg)
parent.set_statusmsg(msg)
@ -192,7 +192,7 @@ def loadproject(parent, filename):
"""Load a project file."""
try:
msg = loadproject_msg(parent, filename)
except StandardError, errmsg:
except StandardError as errmsg:
args = dict(filename=filename, err=errmsg)
msg = _("Could not load project %(filename)s: %(err)s") % args
parent.set_statusmsg(msg)

View file

@ -45,7 +45,7 @@ def decode (page):
fp = StringIO(zlib.decompress(content))
else:
fp = gzip.GzipFile('', 'rb', 9, StringIO(content))
except zlib.error, msg:
except zlib.error as msg:
log.debug(LOG_CHECK, "uncompressing had error "
"%s, assuming non-compressed content", str(msg))
fp = StringIO(content)

View file

@ -131,7 +131,7 @@ def checklink (form=None, env=os.environ):
form = {}
try:
checkform(form, env)
except LCFormError, errmsg:
except LCFormError as errmsg:
log(env, errmsg)
yield encode(format_error(errmsg))
return
@ -199,7 +199,7 @@ def checkform (form, env):
# XXX this is not thread-safe, so think of something else
locale.setlocale(locale.LC_ALL, localestr)
init_i18n()
except locale.Error, errmsg:
except locale.Error as errmsg:
log(env, "could not set locale %r: %s" % (localestr, errmsg))
else:
raise LCFormError(_("unsupported language %r") % lang)

View file

@ -88,7 +88,7 @@ class IfConfig (object):
"""Get interface address."""
try:
result = self._ioctl(func, self._getifreq(ifname))
except IOError, msg:
except IOError as msg:
log.warn(LOG_CHECK,
"error getting addr for interface %r: %s", ifname, msg)
return None
@ -113,7 +113,7 @@ class IfConfig (object):
try:
result = self._ioctl(self.SIOCGIFCONF, ifreq)
break
except IOError, msg:
except IOError as msg:
# in case of EINVAL the buffer size was too small
if msg[0] != errno.EINVAL or bufsize == max_bufsize:
raise
@ -139,7 +139,7 @@ class IfConfig (object):
"""Get the flags for an interface"""
try:
result = self._ioctl(self.SIOCGIFFLAGS, self._getifreq(ifname))
except IOError, msg:
except IOError as msg:
log.warn(LOG_CHECK,
"error getting flags for interface %r: %s", ifname, msg)
return 0

View file

@ -26,7 +26,7 @@ if socket.has_ipv6:
try:
socket.socket(socket.AF_INET6, socket.SOCK_STREAM).close()
has_ipv6 = True
except socket.error, msg:
except socket.error as msg:
# only catch these one:
# socket.error: (97, 'Address family not supported by protocol')
# socket.error: (10047, 'Address family not supported by protocol')

View file

@ -14,6 +14,7 @@
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from __future__ import print_function
import re
import linecache
import time
@ -49,7 +50,7 @@ def _trace (frame, event, arg):
_trace_line(frame, event, arg)
elif event in ('return', 'c_return'):
_trace_line(frame, event, arg)
print " return:", arg
print(" return:", arg)
#elif event in ('exception', 'c_exception'):
# _trace_line(frame, event, arg)
return _trace
@ -80,7 +81,7 @@ def _trace_line (frame, event, arg):
tid = thread.get_ident()
tname = threading.currentThread().getName()
args = (tid, tname, time.time(), line.rstrip(), name, lineno)
print "THREAD(%d) %r %.2f %s # %s:%d" % args
print("THREAD(%d) %r %.2f %s # %s:%d" % args)
def trace_on (full=False):

View file

@ -51,9 +51,12 @@ def has_word ():
if not has_win32com:
return False
try:
import _winreg
key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, "Word.Application")
_winreg.CloseKey(key)
import _winreg as winreg
except ImportError:
import winreg
try:
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "Word.Application")
winreg.CloseKey(key)
return True
except (EnvironmentError, ImportError):
pass
@ -91,12 +94,15 @@ def close_wordfile (doc):
def get_shell_folder (name):
"""Get Windows Shell Folder locations from the registry."""
import _winreg
lm = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
try:
key = _winreg.OpenKey(lm, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
import _winreg as winreg
except ImportError:
import winreg
lm = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
try:
key = winreg.OpenKey(lm, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
try:
return _winreg.QueryValueEx(key, name)[0]
return winreg.QueryValueEx(key, name)[0]
finally:
key.Close()
finally:

View file

@ -220,7 +220,7 @@ def try_compile_re (arg):
message and exit."""
try:
return re.compile(arg)
except re.error, msg:
except re.error as msg:
log.error(LOG_CMDLINE,
_("Syntax error in %(arg)r: %(msg)s") % {"arg": arg, "msg": msg})
sys.exit(1)
@ -488,7 +488,7 @@ try:
log.warn(LOG_CMDLINE,
_("Unreadable config file: %r"), options.configfile)
config.read(files=files)
except linkcheck.LinkCheckerError, msg:
except linkcheck.LinkCheckerError as msg:
# config error
print_usage(str(msg))
linkcheck.drop_privileges()

View file

@ -33,7 +33,7 @@ It includes the following features:
Because of all the features, this script is nasty and big.
Change it very carefully.
"""
from __future__ import print_function
import sys
if not (hasattr(sys, 'version_info') or
sys.version_info < (2, 7, 0, 'final', 0)):
@ -264,11 +264,11 @@ def generate_dmg_image (dist_dir):
"""Generate .dmg image."""
imgPath = os.path.join(dist_dir, "%s-%s.dmg" % (AppName, AppVersion))
tmpImgPath = os.path.join(dist_dir, "%s.tmp.dmg" % AppName)
print "*** generating temporary DMG image ***"
print("*** generating temporary DMG image ***")
args = ['hdiutil', 'create', '-srcfolder', dist_dir, '-fs', 'HFSX',
'-volname', AppName, '-format', 'UDZO', tmpImgPath]
subprocess.check_call(args)
print "*** generating final DMG image ***"
print("*** generating final DMG image ***")
args = ['hdiutil', 'convert', tmpImgPath, '-format', 'UDZO',
'-imagekey', 'zlib-level=9', '-o', imgPath]
subprocess.check_call(args)
@ -279,7 +279,7 @@ def sign_the_code (dist_dir):
"""Sign the OSX application code."""
app_dir = os.path.join(dist_dir, "%s.app" % AppName)
args = ['codesign', '-s', myname, '-v', app_dir]
print "*** signing the application code ***"
print("*** signing the application code ***")
subprocess.check_call(args)
@ -541,7 +541,7 @@ def check_manifest ():
try:
f = open('MANIFEST')
except Exception:
print '\n*** SOURCE WARNING: The MANIFEST file is missing!'
print('\n*** SOURCE WARNING: The MANIFEST file is missing!')
return
try:
manifest = [l.strip() for l in f.readlines() if not l.startswith('#')]
@ -550,9 +550,9 @@ def check_manifest ():
err = [line for line in manifest if not os.path.exists(line)]
if err:
n = len(manifest)
print '\n*** SOURCE WARNING: There are files missing (%d/%d found)!'%(
n - len(err), n)
print 'Missing:', '\nMissing: '.join(err)
print('\n*** SOURCE WARNING: There are files missing (%d/%d found)!' %
(n - len(err), n))
print('\nMissing: '.join(err))
class MyBuild (build, object):
@ -709,48 +709,48 @@ class InnoScript:
def write_inno_script (self, fd):
"""Write Inno script contents."""
print >> fd, "; WARNING: This script has been created by py2exe. Changes to this script"
print >> fd, "; will be overwritten the next time py2exe is run!"
print >> fd, "[Setup]"
print >> fd, "AppName=%s" % self.name
print >> fd, "AppVerName=%s %s" % (self.name, self.version)
print >> fd, r"DefaultDirName={pf}\%s" % self.name
print >> fd, "DefaultGroupName=%s" % self.name
print >> fd, "OutputBaseFilename=%s" % self.distfilebase
print >> fd, "OutputDir=.."
print >> fd, "SetupIconFile=%s" % self.icon
print >> fd, "UninstallDisplayIcon=%s" % self.icon
print >> fd
print("; WARNING: This script has been created by py2exe. Changes to this script", file=fd)
print("; will be overwritten the next time py2exe is run!", file=fd)
print("[Setup]", file=fd)
print("AppName=%s" % self.name, file=fd)
print("AppVerName=%s %s" % (self.name, self.version), file=fd)
print(r"DefaultDirName={pf}\%s" % self.name, file=fd)
print("DefaultGroupName=%s" % self.name, file=fd)
print("OutputBaseFilename=%s" % self.distfilebase, file=fd)
print("OutputDir=..", file=fd)
print("SetupIconFile=%s" % self.icon, file=fd)
print("UninstallDisplayIcon=%s" % self.icon, file=fd)
print(file=fd)
# Customize some messages
print >> fd, "[Messages]"
print >> fd, "ConfirmUninstall=Are you sure you want to remove %1? Note that user-specific configuration files of %1 are not removed."
print >> fd, "BeveledLabel=DON'T PANIC"
print >> fd
print("[Messages]", file=fd)
print("ConfirmUninstall=Are you sure you want to remove %1? Note that user-specific configuration files of %1 are not removed.", file=fd)
print("BeveledLabel=DON'T PANIC", file=fd)
print(file=fd)
# List of source files
files = self.windows_exe_files + \
self.console_exe_files + \
self.service_exe_files + \
self.comserver_files + \
self.lib_files
print >> fd, '[Files]'
print('[Files]', file=fd)
for path in files:
print >> fd, r'Source: "%s"; DestDir: "{app}\%s"; Flags: ignoreversion' % (path, os.path.dirname(path))
print >> fd
print(r'Source: "%s"; DestDir: "{app}\%s"; Flags: ignoreversion' % (path, os.path.dirname(path)), file=fd)
print(file=fd)
# Set icon filename
print >> fd, '[Icons]'
print('[Icons]', file=fd)
for path in self.windows_exe_files:
print >> fd, r'Name: "{group}\%s"; Filename: "{app}\%s"' % \
(self.name, path)
print >> fd, r'Name: "{group}\Uninstall %s"; Filename: "{uninstallexe}"' % self.name
print >> fd
print(r'Name: "{group}\%s"; Filename: "{app}\%s"' % \
(self.name, path), file=fd)
print(r'Name: "{group}\Uninstall %s"; Filename: "{uninstallexe}"' % self.name, file=fd)
print(file=fd)
# Uninstall registry keys
print >> fd, '[Registry]'
print >> fd, r'Root: HKCU; Subkey: "Software\Bastian\LinkChecker"; Flags: uninsdeletekey'
print >> fd
print('[Registry]', file=fd)
print(r'Root: HKCU; Subkey: "Software\Bastian\LinkChecker"; Flags: uninsdeletekey', file=fd)
print(file=fd)
# Uninstall optional log files
print >> fd, '[UninstallDelete]'
print >> fd, r'Type: files; Name: "{pf}\%s\linkchecker*.exe.log"' % self.name
print >> fd
print('[UninstallDelete]', file=fd)
print(r'Type: files; Name: "{pf}\%s\linkchecker*.exe.log"' % self.name, file=fd)
print(file=fd)
def compile (self):
"""Compile Inno script with iscc.exe."""
@ -765,7 +765,7 @@ class InnoScript:
cmd = ['signtool.exe', 'sign', '/f', pfxfile, self.distfile]
subprocess.check_call(cmd)
else:
print "No signed installer: certificate %s not found." % pfxfile
print("No signed installer: certificate %s not found." % pfxfile)
try:
from py2exe.build_exe import py2exe as py2exe_build
@ -778,16 +778,16 @@ try:
"""Generate py2exe installer."""
# First, let py2exe do it's work.
py2exe_build.run(self)
print "*** preparing the inno setup script ***"
print("*** preparing the inno setup script ***")
lib_dir = self.lib_dir
dist_dir = self.dist_dir
# create the Installer, using the files py2exe has created.
script = InnoScript(lib_dir, dist_dir, self.windows_exe_files,
self.console_exe_files, self.service_exe_files,
self.comserver_files, self.lib_files)
print "*** creating the inno setup script ***"
print("*** creating the inno setup script ***")
script.create()
print "*** compiling the inno setup script ***"
print("*** compiling the inno setup script ***")
script.compile()
script.sign()
except ImportError: