# We don't want people using this class by itself.
if self.__class__ is KickstartCommand:
- raise TypeError, "KickstartCommand is an abstract class."
+ raise TypeError ("KickstartCommand is an abstract class.")
KickstartObject.__init__(self, *args, **kwargs)
"""Parse the list of args and set data on the KickstartCommand object.
This method must be provided by all subclasses.
"""
- raise TypeError, "parse() not implemented for KickstartCommand"
+ raise TypeError ("parse() not implemented for KickstartCommand")
def apply(self, instroot="/"):
"""Write out the configuration related to the KickstartCommand object.
def __init__(self, writePriority=None, *args, **kwargs):
# We don't want people using this class by itself.
if self.__class__ is KickstartCommand:
- raise TypeError, "DeprecatedCommand is an abstract class."
+ raise TypeError ("DeprecatedCommand is an abstract class.")
# Create a new DeprecatedCommand instance.
KickstartCommand.__init__(self, writePriority, *args, **kwargs)
# We don't want people using this class by itself.
if self.__class__ is BaseHandler:
- raise TypeError, "BaseHandler is an abstract class."
+ raise TypeError ("BaseHandler is an abstract class.")
KickstartObject.__init__(self, *args, **kwargs)
cmd = args[0]
if not self.commands.has_key(cmd):
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd))
+ raise KickstartParseError (formatErrorMsg(lineno, msg=_("Unknown command: %s" % cmd)))
elif self.commands[cmd] != None:
self.commands[cmd].currentCmd = cmd
self.commands[cmd].currentLine = self.currentLine
def __init__(self, *args, **kwargs):
"""Create a new BaseData instance.
-
- lineno -- Line number in the ks-file where this object was defined
+
+ lineno -- Line number in the ks-file where this object was defined
"""
# We don't want people using this class by itself.
if self.__class__ is BaseData:
- raise TypeError, "BaseData is an abstract class."
+ raise TypeError ("BaseData is an abstract class.")
KickstartObject.__init__(self, *args, **kwargs)
self.lineno = 0
def parse(self, args):
if len(args) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "autopart")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "autopart"))
self.autopart = True
return self
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) != 2:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("device command requires two arguments: module type and name"))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("device command requires two arguments: module type and name")))
self.moduleOpts = opts.moduleOpts
self.type = extra[0]
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("%s command requires a single argument: %s") % ("device", "module name"))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("%s command requires a single argument: %s") % ("device", "module name")))
dd = F8_DeviceData()
self._setToObj(self.op, opts, dd)
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % self.currentCmd)
+ raise KickstartParseError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % self.currentCmd))
if self.currentCmd == "cmdline":
self.displayMode = DISPLAY_MODE_CMDLINE
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one partition may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one partition may be specified for driverdisk command.")))
if len(extra) == 1 and opts.source:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --source and partition may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --source and partition may be specified for driverdisk command.")))
if not extra and not opts.source:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of --source or partition must be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of --source or partition must be specified for driverdisk command.")))
ddd = self.handler.DriverDiskData()
self._setToObj(self.op, opts, ddd)
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one partition may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one partition may be specified for driverdisk command.")))
if len(extra) == 1 and opts.source:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --source and partition may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --source and partition may be specified for driverdisk command.")))
elif len(extra) == 1 and opts.biospart:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --biospart and partition may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --biospart and partition may be specified for driverdisk command.")))
elif opts.source and opts.biospart:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --biospart and --source may be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --biospart and --source may be specified for driverdisk command.")))
if not extra and not opts.source and not opts.biospart:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of --source, --biospart, or partition must be specified for driverdisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of --source, --biospart, or partition must be specified for driverdisk command.")))
ddd = self.handler.DriverDiskData()
self._setToObj(self.op, opts, ddd)
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
mapping = {"command": "fcoe", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping))
self._setToObj(self.op, opts, zd)
zd.lineno = self.lineno
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
-
+
if len(extra) != 0:
mapping = {"command": "firewall", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping)
-
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping))
+
self._setToSelf(self.op, opts)
return self
if errorCheck:
if (len(self.ignoredisk) == 0 and len(self.onlyuse) == 0) or (len(self.ignoredisk) > 0 and (len(self.onlyuse) > 0)):
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of --drives or --only-use must be specified for ignoredisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of --drives or --only-use must be specified for ignoredisk command.")))
return retval
if self.interactive:
howmany += 1
if howmany != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of --drives , --only-use , or --interactive must be specified for ignoredisk command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of --drives , --only-use , or --interactive must be specified for ignoredisk command.")))
return retval
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "interactive")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "interactive"))
self.interactive = True
return self
if len(extra) != 0:
mapping = {"command": "iscsi", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping))
dd = self.handler.IscsiData()
self._setToObj(self.op, opts, dd)
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "iscsiname")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "iscsiname"))
self.iscsiname = extra[0]
return self
if self.skip:
self.key = KS_INSTKEY_SKIP
elif len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "key")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "key"))
else:
self.key = extra[0]
return op
def parse(self, args):
- (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
+ (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "keyboard")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "keyboard"))
self.keyboard = extra[0]
return self
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "lang")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "lang"))
self.lang = extra[0]
return self
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "lilocheck")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "lilocheck"))
self.check = True
return self
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if opts.port and not opts.host:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=_("Can't specify --port without --host."))
+ raise KickstartParseError (formatErrorMsg(self.lineno, msg=_("Can't specify --port without --host.")))
self._setToSelf(self.op, opts)
return self
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) == 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Mount point required for %s") % "logvol")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Mount point required for %s") % "logvol"))
lvd = self.handler.LogVolData()
self._setToObj(self.op, opts, lvd)
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "mediacheck")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "mediacheck"))
self.mediacheck = True
return self
if self.currentCmd == "harddrive":
if self.biospart is None and self.partition is None or \
self.biospart is not None and self.partition is not None:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of biospart or partition options must be specified."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of biospart or partition options must be specified.")))
return self
if extra:
mapping = {"cmd": "monitor", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(cmd)s command: %(options)s") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(cmd)s command: %(options)s") % mapping))
self._setToSelf(self.op, opts)
return self
self._setToSelf(self.op, opts)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "mouse")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s requires one argument") % "mouse"))
self.mouse = extra[0]
return self
for path in mpath.paths:
if path.device == dd.device:
mapping = {"device": path.device, "multipathdev": path.mpdev}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Device '%(device)s' is already used in multipath '%(multipathdev)s'") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Device '%(device)s' is already used in multipath '%(multipathdev)s'") % mapping))
if mpath.name == dd.mpdev:
parent = x
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) == 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Mount point required for %s") % "raid")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Mount point required for %s") % "raid"))
if len(extra) == 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Partitions required for %s") % "raid")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Partitions required for %s") % "raid"))
rd = self.handler.RaidData()
self._setToObj(self.op, opts, rd)
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
-
+
if len(extra) != 0:
mapping = {"command": "repo", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping))
# This is lame, but I can't think of a better way to make sure only
# one of these two is specified.
if opts.baseurl and opts.mirrorlist:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --baseurl and --mirrorlist may be specified for repo command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --baseurl and --mirrorlist may be specified for repo command.")))
if self.urlRequired and not opts.baseurl and not opts.mirrorlist:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("One of --baseurl or --mirrorlist must be specified for repo command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("One of --baseurl or --mirrorlist must be specified for repo command.")))
rd = self.handler.RepoData()
self._setToObj(self.op, opts, rd)
def methodToRepo(self):
if not self.handler.method.url:
- raise KickstartError, formatErrorMsg(self.handler.method.lineno, msg=_("Method must be a url to be added to the repo list."))
+ raise KickstartError (formatErrorMsg(self.handler.method.lineno, msg=_("Method must be a url to be added to the repo list.")))
reponame = "ks-method-url"
repourl = self.handler.method.url
rd = self.handler.RepoData(name=reponame, baseurl=repourl)
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if opts.nomount and opts.romount:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Only one of --nomount and --romount may be specified for rescue command."))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Only one of --nomount and --romount may be specified for rescue command.")))
self._setToSelf(self.op, opts)
self.rescue = True
self._setToSelf(self.op, opts)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "rootpw")
+ raise KickstartValueError ( formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "rootpw"))
self.password = extra[0]
return self
self._setToSelf(self.op, opts)
if len(self.disabled) == 0 and len(self.enabled) == 0:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=_("One of --disabled or --enabled must be provided."))
+ raise KickstartParseError (formatErrorMsg(self.lineno, msg=_("One of --disabled or --enabled must be provided.")))
return self
def parse(self, args):
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "skipx")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "skipx"))
self.skipx = True
return self
ud.lineno = self.lineno
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "sshpw")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "sshpw"))
ud.password = extra[0]
if ud in self.dataList():
self._setToSelf(self.op, opts)
if len(extra) != 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "timezone")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("A single argument is expected for the %s command") % "timezone"))
self.timezone = extra[0]
return self
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 1:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s only takes one argument") % "updates")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s only takes one argument") % "updates"))
elif len(extra) == 0:
self.url = "floppy"
else:
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "upgrade")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "upgrade"))
if self.currentCmd == "upgrade":
self.upgrade = True
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "upgrade")
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "upgrade"))
if (opts.root_device is not None) and (opts.root_device == ""):
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not accept empty parameter %s") % ("upgrade", "--root-device"))
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not accept empty parameter %s") % ("upgrade", "--root-device")))
else:
self.root_device = opts.root_device
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if extra:
mapping = {"command": "xconfig", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=_("Unexpected arguments to %(command)s command: %(options)s") % mapping))
self._setToSelf(self.op, opts)
return self
(opts, extra) = self.op.parse_args(args=args, lineno=self.lineno)
if len(extra) > 0:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "zerombr")
+ raise KickstartParseError (formatErrorMsg(self.lineno, msg=_("Kickstart command %s does not take any arguments") % "zerombr"))
self.zerombr = True
return self
def error(self, msg):
if self.lineno != None:
- raise KickstartParseError, formatErrorMsg(self.lineno, msg=msg)
+ raise KickstartParseError ( formatErrorMsg(self.lineno, msg=msg))
else:
- raise KickstartParseError, msg
+ raise KickstartParseError ( msg)
def keys(self):
retval = []
for option in filter(lambda o: isinstance(o, Option), self.option_list):
if option.required and not seen(self, option):
- raise KickstartValueError, formatErrorMsg(self.lineno, _("Option %s is required") % option)
+ raise KickstartValueError (formatErrorMsg(self.lineno, _("Option %s is required") % option))
elif seen(self, option) and usedTooNew(self, option):
mapping = {"option": option, "intro": versionToString(option.introduced),
"version": versionToString(self.version)}
try:
ksurl = ll.split(' ')[1]
except:
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll)
+ raise KickstartParseError (formatErrorMsg(lineno, msg=_("Illegal url for %%ksappend: %s") % ll))
try:
url = grabber.urlopen(ksurl)
- except grabber.URLGrabError, e:
- raise KickstartError, formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % e.strerror)
+ except grabber.URLGrabError as e:
+ raise KickstartError (formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file: %s") % e.strerror))
else:
# Sanity check result. Sometimes FTP doesn't catch a file
# is missing.
try:
if url.size < 1:
- raise KickstartError, formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file"))
+ raise KickstartError (formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file")))
except:
- raise KickstartError, formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file"))
+ raise KickstartError (formatErrorMsg(lineno, msg=_("Unable to open %%ksappend file")))
# If that worked, write the remote file to the output kickstart
# file in one burst. Then close everything up to get ready to
"""
try:
fh = urlopen(f)
- except grabber.URLGrabError, e:
- raise KickstartError, formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror)
+ except grabber.URLGrabError as e:
+ raise KickstartError (formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror))
rc = _preprocessStateMachine (iter(fh.readlines()))
fh.close()
(opts, extra) = op.parse_args(args=line.split())
if opts.nodefaults and opts.optional:
- raise KickstartValueError, _("Group cannot specify both --nodefaults and --optional")
+ raise KickstartValueError (_("Group cannot specify both --nodefaults and --optional"))
# If the group name has spaces in it, we have to put it back together
# now.
handle it.
"""
if not obj.sectionOpen:
- raise TypeError, "no sectionOpen given for section %s" % obj
+ raise TypeError ("no sectionOpen given for section %s" % obj)
if not obj.sectionOpen.startswith("%"):
- raise TypeError, "section %s tag does not start with a %%" % obj.sectionOpen
+ raise TypeError ("section %s tag does not start with a %%" % obj.sectionOpen)
self._sections[obj.sectionOpen] = obj
if line == "":
# This section ends at the end of the file.
if self.version >= version.F8:
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Section does not end with %%end."))
+ raise KickstartParseError (formatErrorMsg(lineno, msg=_("Section does not end with %%end.")))
self._finalize(obj)
except StopIteration:
elif args and (self._validState(args[0]) or args[0] in ["%include", "%ksappend"]):
# This is an unterminated section.
if self.version >= version.F8:
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Section does not end with %%end."))
+ raise KickstartParseError (formatErrorMsg(lineno, msg=_("Section does not end with %%end.")))
# Finish up. We do not process the header here because
# kicking back out to STATE_COMMANDS will ensure that happens.
"""
try:
fn()
- except Exception, msg:
+ except Exception as msg:
if self.errorsAreFatal:
raise
else:
- print msg
+ print (msg)
def _isBlankOrComment(self, line):
return line.isspace() or line == "" or line.lstrip()[0] == '#'
continue
if len(args) == 1 or not args[1]:
- raise KickstartParseError, formatErrorMsg(lineno)
+ raise KickstartParseError (formatErrorMsg(lineno))
self._includeDepth += 1
# here.
newSection = args[0]
if not self._validState(newSection):
- raise KickstartParseError, formatErrorMsg(lineno, msg=_("Unknown kickstart section: %s" % newSection))
+ raise KickstartParseError (formatErrorMsg(lineno, msg=_("Unknown kickstart section: %s" % newSection)))
self._state = newSection
obj = self._sections[self._state]
try:
s = urlread(f)
- except grabber.URLGrabError, e:
- raise KickstartError, formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror)
+ except grabber.URLGrabError as e:
+ raise KickstartError (formatErrorMsg(0, msg=_("Unable to open input kickstart file: %s") % e.strerror))
self.readKickstartFromString(s, reset=False)
DEBUG = None
-try:
+try:
from cStringIO import StringIO
-except ImportError, msg:
+except ImportError as msg:
from StringIO import StringIO
class RangeError(IOError):
"""Error raised when an unsatisfiable range is requested."""
pass
-
+
class HTTPRangeHandler(urllib2.BaseHandler):
"""Handler that enables HTTP Range headers.
-
+
This was extremely simple. The Range header is a HTTP feature to
- begin with so all this class does is tell urllib2 that the
- "206 Partial Content" reponse from the HTTP server is what we
+ begin with so all this class does is tell urllib2 that the
+ "206 Partial Content" reponse from the HTTP server is what we
expected.
-
+
Example:
import urllib2
import byterange
-
+
range_handler = range.HTTPRangeHandler()
opener = urllib2.build_opener(range_handler)
-
+
# install it
urllib2.install_opener(opener)
-
+
# create Request and set Range header
req = urllib2.Request('http://www.python.org/')
req.header['Range'] = 'bytes=30-50'
# byte in the range. the following will return only 7 bytes.
>>> fo.read(30)
"""
-
+
def __init__(self, fo, rangetup):
"""Create a RangeableFileObject.
- fo -- a file like object. only the read() method need be
- supported but supporting an optimized seek() is
+ fo -- a file like object. only the read() method need be
+ supported but supporting an optimized seek() is
preferable.
rangetup -- a (firstbyte,lastbyte) tuple specifying the range
to work over.
(self.firstbyte, self.lastbyte) = range_tuple_normalize(rangetup)
self.realpos = 0
self._do_seek(self.firstbyte)
-
+
def __getattr__(self, name):
"""This effectively allows us to wrap at the instance level.
Any attribute not found in _this_ object will be searched for
in self.fo. This includes methods."""
if hasattr(self.fo, name):
return getattr(self.fo, name)
- raise AttributeError, name
-
+ raise AttributeError (name)
+
def tell(self):
"""Return the position within the range.
- This is different from fo.seek in that position 0 is the
+ This is different from fo.seek in that position 0 is the
first byte position of the range tuple. For example, if
this object was created with a range tuple of (500,899),
tell() will return 0 when at byte position 500 of the file.
"""
return (self.realpos - self.firstbyte)
-
+
def seek(self,offset,whence=0):
"""Seek within the byte range.
Positioning is identical to that described under tell().
def ftp_open(self, req):
host = req.get_host()
if not host:
- raise IOError, ('ftp error', 'no host given')
+ raise IOError ('ftp error', 'no host given')
host, port = splitport(host)
if port is None:
port = ftplib.FTP_PORT
host = unquote(host)
user = unquote(user or '')
passwd = unquote(passwd or '')
-
+
try:
host = socket.gethostbyname(host)
- except socket.error, msg:
+ except socket.error as msg:
raise urllib2.URLError(msg)
path, attrs = splitattr(req.get_selector())
dirs = path.split('/')
retrlen = lb - fb
fp = RangeableFileObject(fp, (0,retrlen))
# -- range support modifications end here
-
+
headers = ""
mtype = mimetypes.guess_type(req.get_full_url())[0]
if mtype:
sf = StringIO(headers)
headers = mimetools.Message(sf)
return addinfourl(fp, headers, req.get_full_url())
- except ftplib.all_errors, msg:
- raise IOError, ('ftp error', msg), sys.exc_info()[2]
+ except ftplib.all_errors as msg:
+ raise IOError (('ftp error', msg), sys.exc_info()[2])
def connect_ftp(self, user, passwd, host, port, dirs):
fw = ftpwrapper(user, passwd, host, port, dirs)
# Use nlst to see if the file exists at all
try:
self.ftp.nlst(file)
- except ftplib.error_perm, reason:
- raise IOError, ('ftp error', reason), sys.exc_info()[2]
+ except ftplib.error_perm as reason:
+ raise IOError (('ftp error', reason), sys.exc_info()[2])
# Restore the transfer mode!
self.ftp.voidcmd(cmd)
# Try to retrieve as a file
try:
cmd = 'RETR ' + file
conn = self.ftp.ntransfercmd(cmd, rest)
- except ftplib.error_perm, reason:
+ except ftplib.error_perm as reason:
if str(reason)[:3] == '501':
# workaround for REST not supported error
fp, retrlen = self.retrfile(file, type)
fp = RangeableFileObject(fp, (rest,''))
return (fp, retrlen)
elif str(reason)[:3] != '550':
- raise IOError, ('ftp error', reason), sys.exc_info()[2]
+ raise IOError (('ftp error', reason), sys.exc_info()[2])
if not conn:
# Set transfer mode to ASCII!
self.ftp.voidcmd('TYPE A')
try:
from i18n import _
-except ImportError, msg:
+except ImportError as msg:
def _(st): return st
try:
from httplib import HTTPException
-except ImportError, msg:
+except ImportError as msg:
HTTPException = None
try:
import keepalive
from keepalive import HTTPHandler, HTTPSHandler
have_keepalive = True
-except ImportError, msg:
+except ImportError as msg:
have_keepalive = False
try:
from byterange import HTTPRangeHandler, HTTPSRangeHandler, \
FileRangeHandler, FTPRangeHandler, range_tuple_normalize, \
range_tuple_to_header, RangeError
-except ImportError, msg:
+except ImportError as msg:
range_handlers = ()
RangeError = None
have_range = 0
user_pass, host = host.split('@', 1)
if ':' in user_pass:
user, password = user_pass.split(':', 1)
- except ValueError, e:
+ except ValueError as e:
raise URLGrabError(1, _('Bad URL: %s') % url)
if DEBUG: DEBUG.info('adding HTTP auth: %s, XXXXXXXX', user)
auth_handler.add_password(None, host, user, password)
if delegate is None:
self._set_defaults()
self._set_attributes(**kwargs)
-
+
def __getattr__(self, name):
if self.delegate and hasattr(self.delegate, name):
return getattr(self.delegate, name)
- raise AttributeError, name
-
+ raise AttributeError (name)
+
def raw_throttle(self):
- """Calculate raw throttle value from throttle and bandwidth
+ """Calculate raw throttle value from throttle and bandwidth
values.
"""
- if self.throttle <= 0:
+ if self.throttle <= 0:
return 0
- elif type(self.throttle) == type(0):
+ elif type(self.throttle) == type(0):
return float(self.throttle)
else: # throttle is a float
return self.bandwidth * self.throttle
-
+
def derive(self, **kwargs):
"""Create a derived URLGrabberOptions instance.
This method creates a new instance and overrides the
options specified in kwargs.
"""
return URLGrabberOptions(delegate=self, **kwargs)
-
+
def _set_attributes(self, **kwargs):
"""Update object attributes with those provided in kwargs."""
self.__dict__.update(kwargs)
r = apply(func, (opts,) + args, {})
if DEBUG: DEBUG.info('success')
return r
- except URLGrabError, e:
+ except URLGrabError as e:
exception = e
callback = opts.failure_callback
retrycode = e.errno
- except KeyboardInterrupt, e:
+ except KeyboardInterrupt as e:
exception = e
callback = opts.interrupt_callback
cb_func(obj, *cb_args, **cb_kwargs)
if (opts.retry is None) or (tries == opts.retry):
- if DEBUG: DEBUG.info('retries exceeded, re-raising')
+ if DEBUG:DEBUG.info('retries exceeded, re-raising')
raise
if (retrycode is not None) and (retrycode not in opts.retrycodes):
- if DEBUG: DEBUG.info('retrycode (%i) not in list %s, re-raising',
+ if DEBUG:DEBUG.info('retrycode (%i) not in list %s, re-raising',
retrycode, opts.retrycodes)
raise
-
+
def urlopen(self, url, **kwargs):
"""open the url and return a file object
- If a progress object or throttle value specified when this
- object was created, then a special file object will be
- returned that supports them. The file object can be treated
+ If a progress object or throttle value specified when this
+ object was created, then a special file object will be
+ returned that supports them. The file object can be treated
like any other file object.
"""
opts = self.opts.derive(**kwargs)
- (url,parts) = opts.urlparser.parse(url, opts)
+ (url,parts) = opts.urlparser.parse(url, opts)
def retryfunc(opts, url):
return URLGrabberFileObject(url, filename=None, opts=opts)
return self._retry(opts, retryfunc, url)
-
+
def urlgrab(self, url, filename=None, **kwargs):
"""grab the file at <url> and make a local copy at <filename>
If filename is none, the basename of the url is used.
- urlgrab returns the filename of the local file, which may be
+ urlgrab returns the filename of the local file, which may be
different from the passed-in filename if copy_local == 0.
"""
opts = self.opts.derive(**kwargs)
- (url,parts) = opts.urlparser.parse(url, opts)
+ (url,parts) = opts.urlparser.parse(url, opts)
(scheme, host, path, parm, query, frag) = parts
if filename is None:
filename = os.path.basename( urllib.unquote(path) )
if scheme == 'file' and not opts.copy_local:
- # just return the name of the local file - don't make a
+ # just return the name of the local file - don't make a
# copy currently
path = urllib.url2pathname(path)
if host:
self._amount_read = 0
self._opener = None
self._do_open()
-
+
def __getattr__(self, name):
"""This effectively allows us to wrap at the instance level.
Any attribute not found in _this_ object will be searched for
in self.fo. This includes methods."""
if hasattr(self.fo, name):
return getattr(self.fo, name)
- raise AttributeError, name
-
+ raise AttributeError (name)
+
def _get_opener(self):
"""Build a urllib2 OpenerDirector based on request options."""
if self.opts.opener:
else:
fo = opener.open(req)
hdr = fo.info()
- except ValueError, e:
+ except ValueError as e:
raise URLGrabError(1, _('Bad URL: %s') % (e, ))
- except RangeError, e:
+ except RangeError as e:
raise URLGrabError(9, str(e))
- except urllib2.HTTPError, e:
+ except urllib2.HTTPError as e:
new_e = URLGrabError(14, str(e))
new_e.code = e.code
new_e.exception = e
raise new_e
- except IOError, e:
+ except IOError as e:
if hasattr(e, 'reason') and have_socket_timeout and \
isinstance(e.reason, TimeoutError):
raise URLGrabError(12, _('Timeout: %s') % (e, ))
else:
raise URLGrabError(4, _('IOError: %s') % (e, ))
- except OSError, e:
+ except OSError as e:
raise URLGrabError(5, _('OSError: %s') % (e, ))
- except HTTPException, e:
+ except HTTPException as e:
raise URLGrabError(7, _('HTTP Exception (%s): %s') % \
(e.__class__.__name__, e))
else:
return (fo, hdr)
-
+
def _do_grab(self):
"""dump the file to self.filename."""
if self.append: new_fo = open(self.filename, 'ab')
modified_tuple = self.hdr.getdate_tz('last-modified')
modified_stamp = rfc822.mktime_tz(modified_tuple)
os.utime(self.filename, (modified_stamp, modified_stamp))
- except (TypeError,), e: pass
+ except (TypeError,) as e: pass
return size
-
+
def _fill_buffer(self, amt=None):
"""fill the buffer to contain at least 'amt' bytes by reading
from the underlying file object. If amt is None, then it will
(time.time() - self._ttime)
if diff > 0: time.sleep(diff)
self._ttime = time.time()
-
+
# now read some data, up to self._rbufsize
if amt is None: readamount = self._rbufsize
else: readamount = min(amt, self._rbufsize)
try:
new = self.fo.read(readamount)
- except socket.error, e:
+ except socket.error as e:
raise URLGrabError(4, _('Socket Error: %s') % (e, ))
- except TimeoutError, e:
+ except TimeoutError as e:
raise URLGrabError(12, _('Timeout: %s') % (e, ))
- except IOError, e:
+ except IOError as e:
raise URLGrabError(4, _('IOError: %s') %(e,))
newsize = len(new)
if not newsize: break # no more to read
def set_user_agent(new_user_agent):
"""Deprecated. Use: default_grabber.user_agent = new_user_agent"""
default_grabber.user_agent = new_user_agent
-
+
def retrygrab(url, filename=None, copy_local=0, close_connection=0,
progress_obj=None, throttle=None, bandwidth=None,
numtries=3, retrycodes=[-1,2,4,5,6,7], checkfunc=None):
"""Deprecated. Use: urlgrab() with the retry arg instead"""
- kwargs = {'copy_local' : copy_local,
+ kwargs = {'copy_local' : copy_local,
'close_connection' : close_connection,
- 'progress_obj' : progress_obj,
- 'throttle' : throttle,
+ 'progress_obj' : progress_obj,
+ 'throttle' : throttle,
'bandwidth' : bandwidth,
'retry' : numtries,
'retrycodes' : retrycodes,
- 'checkfunc' : checkfunc
+ 'checkfunc' : checkfunc
}
return urlgrab(url, filename, **kwargs)
-
+
#####################################################################
# TESTING
def _main_test():
import sys
try: url, filename = sys.argv[1:3]
except ValueError:
- print 'usage:', sys.argv[0], \
- '<url> <filename> [copy_local=0|1] [close_connection=0|1]'
+ print( 'usage:', sys.argv[0], \
+ '<url> <filename> [copy_local=0|1] [close_connection=0|1]')
sys.exit()
kwargs = {}
set_throttle(1.0)
set_bandwidth(32 * 1024)
- print "throttle: %s, throttle bandwidth: %s B/s" % (default_grabber.throttle,
- default_grabber.bandwidth)
+ print( "throttle: %s, throttle bandwidth: %s B/s" % (default_grabber.throttle,
+ default_grabber.bandwidth))
try: from progress import text_progress_meter
- except ImportError, e: pass
+ except ImportError as e: pass
else: kwargs['progress_obj'] = text_progress_meter()
try: name = apply(urlgrab, (url, filename), kwargs)
- except URLGrabError, e: print e
- else: print 'LOCAL FILE:', name
+ except URLGrabError as e: print( e)
+ else: print( 'LOCAL FILE:', name)
def _retry_test():
import sys
try: url, filename = sys.argv[1:3]
except ValueError:
- print 'usage:', sys.argv[0], \
- '<url> <filename> [copy_local=0|1] [close_connection=0|1]'
+ print( 'usage:', sys.argv[0], \
+ '<url> <filename> [copy_local=0|1] [close_connection=0|1]')
sys.exit()
kwargs = {}
kwargs[k] = int(v)
try: from progress import text_progress_meter
- except ImportError, e: pass
+ except ImportError as e: pass
else: kwargs['progress_obj'] = text_progress_meter()
def cfunc(filename, hello, there='foo'):
- print hello, there
+ print( hello, there)
import random
rnum = random.random()
if rnum < .5:
- print 'forcing retry'
+ print( 'forcing retry')
raise URLGrabError(-1, 'forcing retry')
if rnum < .75:
- print 'forcing failure'
+ print( 'forcing failure')
raise URLGrabError(-2, 'forcing immediate failure')
- print 'success'
+ print( 'success')
return
-
+
kwargs['checkfunc'] = (cfunc, ('hello',), {'there':'there'})
try: name = apply(retrygrab, (url, filename), kwargs)
- except URLGrabError, e: print e
- else: print 'LOCAL FILE:', name
+ except URLGrabError as e: print( e)
+ else: print( 'LOCAL FILE:', name)
def _file_object_test(filename=None):
import random, cStringIO, sys
if filename is None:
filename = __file__
- print 'using file "%s" for comparisons' % filename
+ print( 'using file "%s" for comparisons' % filename)
fo = open(filename)
s_input = fo.read()
fo.close()
fo_input = cStringIO.StringIO(s_input)
fo_output = cStringIO.StringIO()
wrapper = URLGrabberFileObject(fo_input, None, 0)
- print 'testing %-30s ' % testfunc.__name__,
- testfunc(wrapper, fo_output)
+ print( 'testing %-30s ' % testfunc.__name__,
+ testfunc(wrapper, fo_output))
s_output = fo_output.getvalue()
- if s_output == s_input: print 'passed'
- else: print 'FAILED'
-
+ if s_output == s_input: print( 'passed')
+ else: print( 'FAILED')
+
def _test_file_object_smallread(wrapper, fo_output):
while 1:
s = wrapper.read(23)
self._cm.add(host, h, 0)
self._start_transaction(h, req)
r = h.getresponse()
- except (socket.error, httplib.HTTPException), err:
+ except (socket.error, httplib.HTTPException) as err:
raise urllib2.URLError(err)
-
+
# if not a persistent connection, don't try to reuse it
if r.will_close: self._cm.remove(h)
h.putheader('Content-length', '%d' % len(data))
else:
h.putrequest('GET', req.get_selector())
- except (socket.error, httplib.HTTPException), err:
+ except (socket.error, httplib.HTTPException) as err:
raise urllib2.URLError(err)
for args in self.parent.addheaders:
urllib2.install_opener(opener)
pos = {0: 'off', 1: 'on'}
for i in (0, 1):
- print " fancy error handling %s (HANDLE_ERRORS = %i)" % (pos[i], i)
+ print (" fancy error handling %s (HANDLE_ERRORS = %i)" % (pos[i], i))
HANDLE_ERRORS = i
try:
fo = urllib2.urlopen(url)
fo.close()
try: status, reason = fo.status, fo.reason
except AttributeError: status, reason = None, None
- except IOError, e:
- print " EXCEPTION: %s" % e
+ except IOError as e:
+ print (" EXCEPTION: %s" % e)
raise
else:
- print " status = %s, reason = %s" % (status, reason)
+ print (" status = %s, reason = %s" % (status, reason))
HANDLE_ERRORS = orig
hosts = keepalive_handler.open_connections()
- print "open connections:", hosts
+ print( "open connections:", hosts)
keepalive_handler.close_all()
def continuity(url):
import md5
format = '%25s: %s'
-
+
# first fetch the file with the normal http handler
opener = urllib2.build_opener()
urllib2.install_opener(opener)
foo = fo.read()
fo.close()
m = md5.new(foo)
- print format % ('normal urllib', m.hexdigest())
+ print(format % ('normal urllib', m.hexdigest()))
# now install the keepalive handler and try again
opener = urllib2.build_opener(HTTPHandler())
foo = fo.read()
fo.close()
m = md5.new(foo)
- print format % ('keepalive read', m.hexdigest())
+ print(format % ('keepalive read', m.hexdigest()))
fo = urllib2.urlopen(url)
foo = ''
else: break
fo.close()
m = md5.new(foo)
- print format % ('keepalive readline', m.hexdigest())
+ print( format % ('keepalive readline', m.hexdigest()))
def comp(N, url):
- print ' making %i connections to:\n %s' % (N, url)
+ print( ' making %i connections to:\n %s' % (N, url))
sys.stdout.write(' first using the normal urllib handlers')
# first use normal opener
opener = urllib2.build_opener()
urllib2.install_opener(opener)
t1 = fetch(N, url)
- print ' TIME: %.3f s' % t1
+ print( ' TIME: %.3f s' % t1)
sys.stdout.write(' now using the keepalive handler ')
# now install the keepalive handler and try again
opener = urllib2.build_opener(HTTPHandler())
urllib2.install_opener(opener)
t2 = fetch(N, url)
- print ' TIME: %.3f s' % t2
- print ' improvement factor: %.2f' % (t1/t2, )
-
+ print (' TIME: %.3f s' % t2)
+ print( ' improvement factor: %.2f' % (t1/t2, ))
+
def fetch(N, url, delay=0):
import time
lens = []
for i in lens[1:]:
j = j + 1
if not i == lens[0]:
- print "WARNING: inconsistent length on read %i: %i" % (j, i)
+ print( "WARNING: inconsistent length on read %i: %i" % (j, i))
return diff
global DEBUG
dbbackup = DEBUG
class FakeLogger:
- def debug(self, msg, *args): print msg % args
+ def debug(self, msg, *args): print( msg % args)
info = warning = error = debug
DEBUG = FakeLogger()
- print " fetching the file to establish a connection"
+ print( " fetching the file to establish a connection")
fo = urllib2.urlopen(url)
data1 = fo.read()
fo.close()
-
+
i = 20
- print " waiting %i seconds for the server to close the connection" % i
+ print( " waiting %i seconds for the server to close the connection" % i)
while i > 0:
sys.stdout.write('\r %2i' % i)
sys.stdout.flush()
i -= 1
sys.stderr.write('\r')
- print " fetching the file a second time"
+ print( " fetching the file a second time")
fo = urllib2.urlopen(url)
data2 = fo.read()
fo.close()
if data1 == data2:
- print ' data are identical'
+ print( ' data are identical')
else:
- print ' ERROR: DATA DIFFER'
+ print( ' ERROR: DATA DIFFER')
DEBUG = dbbackup
-
+
def test(url, N=10):
- print "checking error hander (do this on a non-200)"
+ print( "checking error hander (do this on a non-200)")
try: error_handler(url)
- except IOError, e:
- print "exiting - exception will prevent further tests"
+ except IOError as e:
+ print( "exiting - exception will prevent further tests")
sys.exit()
- print
- print "performing continuity test (making sure stuff isn't corrupted)"
+ print()
+ print( "performing continuity test (making sure stuff isn't corrupted)")
continuity(url)
- print
- print "performing speed comparison"
+ print()
+ print( "performing speed comparison")
comp(N, url)
- print
- print "performing dropped-connection check"
+ print()
+ print( "performing dropped-connection check")
test_timeout(url)
-
+
if __name__ == '__main__':
import time
import sys
N = int(sys.argv[1])
url = sys.argv[2]
except:
- print "%s <integer> <url>" % sys.argv[0]
+ print( "%s <integer> <url>" % sys.argv[0])
else:
test(url, N)
try:
from i18n import _
-except ImportError, msg:
+except ImportError as msg:
def _(st): return st
class GrabRequest:
if DEBUG: DEBUG.info('MIRROR: trying %s -> %s', url, fullurl)
try:
return func_ref( *(fullurl,), **kwargs )
- except URLGrabError, e:
+ except URLGrabError as e:
if DEBUG: DEBUG.info('MIRROR: failed')
obj = CallbackObject()
obj.exception = e
'E', # exa
'Z', # zetta
'Y'] # yotta
-
+
if SI: step = 1000.0
else: step = 1024.0
thresh = 999
depth = 0
max_depth = len(symbols) - 1
-
+
# we want numbers between 0 and thresh, but don't exceed the length
# of our list. In that event, the formatting will be screwed up,
# but it'll still show the right number.
depth = depth + 1
number = number / step
- if type(number) == type(1) or type(number) == type(1L):
+ if type(number) == type(1) or type(number) == type(1):
# it's an int or a long, which means it didn't get divided,
# which means it's already short enough
format = '%i%s%s'
format = '%.1f%s%s'
else:
format = '%.0f%s%s'
-
+
return(format % (float(number or 0), space, symbols[depth]))
# * Used builtin function (W0141)
# * Invalid name for type (C0103)
# * Popen has no '%s' member (E1101)
-# pylint: disable=W0142, W0612, W0141, C0103, E1101
+# pylint: disable= W0612, C0103, E1101
""" Compression and Archiving
@retval: the path of the compressed file
"""
if not os.path.isfile(file_path):
- raise OSError, "can't compress a file not existed: '%s'" % file_path
+ raise OSError ("can't compress a file not existed: '%s'" % file_path)
try:
func = _COMPRESS_FORMATS[compress_format]
except KeyError:
- raise ValueError, "unknown compress format '%s'" % compress_format
+ raise ValueError ("unknown compress format '%s'" % compress_format)
return func(file_path, True)
def decompress(file_path, decompress_format=None):
@retval: the path of the decompressed file
"""
if not os.path.isfile(file_path):
- raise OSError, "can't decompress a file not existed: '%s'" % file_path
+ raise OSError ("can't decompress a file not existed: '%s'" % file_path)
(file_name, file_ext) = os.path.splitext(file_path)
for key, suffixes in _COMPRESS_SUFFIXES.iteritems():
try:
func = _COMPRESS_FORMATS[decompress_format]
except KeyError:
- raise ValueError, "unknown decompress format '%s'" % decompress_format
+ raise ValueError ("unknown decompress format '%s'" % decompress_format)
return func(file_path, False)
cmdln = ["tar", "-C", target_dir, "-xf", archive_name]
(returncode, stdout, stderr) = _call_external(cmdln)
if returncode != 0:
- raise OSError, os.linesep.join([stdout, stderr])
+ raise OSError (os.linesep.join([stdout, stderr]))
def _imp_tarfile(archive_name, target_name):
""" Archive the directory or the file with tarfile module
@retval: the archiving result
"""
if not os.path.exists(target_name):
- raise OSError, "archive object does not exist: '%s'" % target_name
+ raise OSError ("archive object does not exist: '%s'" % target_name)
for aformat, suffixes in _ARCHIVE_SUFFIXES.iteritems():
if filter(archive_name.endswith, suffixes):
archive_format = aformat
break
else:
- raise ValueError, "unknown archive suffix '%s'" % archive_name
+ raise ValueError ("unknown archive suffix '%s'" % archive_name)
try:
func, kwargs = _ARCHIVE_FORMATS[archive_format]
except KeyError:
- raise ValueError, "unknown archive format '%s'" % archive_format
+ raise ValueError ("unknown archive format '%s'" % archive_format)
archive_name = os.path.abspath(archive_name)
target_name = os.path.abspath(target_name)
raise exception if fail to extract archive
"""
if not os.path.exists(archive_name):
- raise OSError, "archived object does not exist: '%s'" % archive_name
+ raise OSError ("archived object does not exist: '%s'" % archive_name)
archive_name = os.path.abspath(archive_name)
target_name = os.path.abspath(target_name)
if os.path.exists(target_name) and not os.path.isdir(target_name):
- raise OSError, "%s should be directory where extracted files locate"\
- % target_name
+ raise OSError ("%s should be directory where extracted files locate"\
+ % target_name)
if not os.path.exists(target_name):
os.makedirs(target_name)
import subprocess
import rpm
import glob
+import errno
from mic import msger
from mic.utils import errors, proxy, misc
script = script.replace('\r', '')
os.write(tmpfd, script)
os.close(tmpfd)
- os.chmod(tmpfp, 0700)
+ os.chmod(tmpfp, 0o700)
try:
script_fp = os.path.join('/tmp', os.path.basename(tmpfp))
subprocess.call([prog, script_fp, arg], preexec_fn=mychroot)
- except (OSError, IOError), err:
+ except (OSError, IOError) as err:
msger.warning(str(err))
finally:
os.unlink(tmpfp)
pkgmgr.optionals = list(optlist)
map(pkgmgr.selectPackage, pkglist + list(optlist))
pkgmgr.runInstall()
- except (OSError, IOError, errors.CreatorError), err:
+ except (OSError, IOError, errors.CreatorError) as err:
raise errors.BootstrapError("%s" % err)
def run(self, cmd, chdir, rootdir=None, bindmounts=None):
# add additional information to original exception
value, tb = sys.exc_info()[1:]
value = '%s: %s' % (value, ' '.join(cmd))
- raise RuntimeError, value, tb
+ raise RuntimeError (value, tb)
finally:
#if self.logfile and os.path.isfile(self.logfile):
# msger.log(file(self.logfile).read())
globalmounts = setup_chrootenv(chrootdir, bindmounts)
subprocess.call(execute, preexec_fn = mychroot, shell=True)
- except OSError, err:
+ except OSError as err:
raise errors.CreatorError("chroot err: %s" % str(err))
finally:
try:
self.__siteconf = siteconf
self._parse_siteconf(siteconf)
- except ConfigParser.Error, error:
+ except ConfigParser.Error as error:
raise errors.ConfigError("%s" % error)
def __get_siteconf(self):
return self.__siteconf
import tarfile
import glob
import json
+import errno
from datetime import datetime
import rpm
import time
f = open(namefile, "w")
f.write(content)
f.close()
- self.outimage.append(namefile);
+ self.outimage.append(namefile)
# if 'content', save more details
if 'content' in self._recording_pkgs:
os.makedirs(self.workdir)
self.__builddir = tempfile.mkdtemp(dir = self.workdir,
prefix = "imgcreate-")
- except OSError, (err, msg):
+ except OSError as msg:
raise CreatorError("Failed create build directory in %s: %s" %
(self.tmpdir, msg))
def __create_minimal_dev(self):
"""Create a minimal /dev so that we don't corrupt the host /dev"""
origumask = os.umask(0000)
- devices = (('null', 1, 3, 0666),
- ('urandom',1, 9, 0666),
- ('random', 1, 8, 0666),
- ('full', 1, 7, 0666),
- ('ptmx', 5, 2, 0666),
- ('tty', 5, 0, 0666),
- ('zero', 1, 5, 0666))
+ devices = (('null', 1, 3, 0o666),
+ ('urandom',1, 9, 0o666),
+ ('random', 1, 8, 0o666),
+ ('full', 1, 7, 0o666),
+ ('ptmx', 5, 2, 0o666),
+ ('tty', 5, 0, 0o666),
+ ('zero', 1, 5, 0o666))
links = (("/proc/self/fd", "/dev/fd"),
("/proc/self/fd/0", "/dev/stdin"),
#self.__localinst_packages(pkg_manager)
self.__check_packages(pkg_manager)
- BOOT_SAFEGUARD = 256L * 1024 * 1024 # 256M
+ BOOT_SAFEGUARD = 256 * 1024 * 1024 # 256M
checksize = self._root_fs_avail
if checksize:
checksize -= BOOT_SAFEGUARD
if self.multiple_partitions:
pkg_manager._add_prob_flags(rpm.RPMPROB_FILTER_DISKSPACE)
pkg_manager.runInstall(checksize)
- except CreatorError, e:
+ except CreatorError as e:
raise
except KeyboardInterrupt:
raise
msger.info("Running sign scripts ...")
if os.path.exists(self._instroot + "/tmp"):
shutil.rmtree(self._instroot + "/tmp")
- os.mkdir (self._instroot + "/tmp", 0755)
+ os.mkdir (self._instroot + "/tmp", 0o755)
for s in kickstart.get_sign_scripts(self.ks):
(fd, path) = tempfile.mkstemp(prefix = "ks-runscript-",
dir = self._instroot + "/tmp")
os.write(fd, '\n')
os.write(fd, 'exit 0\n')
os.close(fd)
- os.chmod(path, 0700)
+ os.chmod(path, 0o700)
env = self._get_sign_scripts_env()
oldoutdir = os.getcwd()
if p.returncode != 0:
raise CreatorError("Failed to execute %%sign script "
"with '%s'" % (s.interp))
- except OSError, (err, msg):
+ except OSError as msg:
raise CreatorError("Failed to execute %%sign script "
"with '%s' : %s" % (s.interp, msg))
finally:
msger.info("Running post scripts ...")
if os.path.exists(self._instroot + "/tmp"):
shutil.rmtree(self._instroot + "/tmp")
- os.mkdir (self._instroot + "/tmp", 0755)
+ os.mkdir (self._instroot + "/tmp", 0o755)
for s in kickstart.get_post_scripts(self.ks):
(fd, path) = tempfile.mkstemp(prefix = "ks-postscript-",
dir = self._instroot + "/tmp")
os.write(fd, '\n')
os.write(fd, 'exit 0\n')
os.close(fd)
- os.chmod(path, 0700)
+ os.chmod(path, 0o700)
env = self._get_post_scripts_env(s.inChroot)
if 'PATH' not in env:
if p.returncode != 0:
raise CreatorError("Failed to execute %%post script "
"with '%s'" % (s.interp))
- except OSError, (err, msg):
+ except OSError as msg:
raise CreatorError("Failed to execute %%post script "
"with '%s' : %s" % (s.interp, msg))
finally:
# find . | cpio --create --'format=newc' | gzip > ../ramdisk.img
runner.show('find . | cpio --create %s | gzip > %s' % (item['cpioopts'], tmp_cpio_imgfile))
os.chdir(oldoutdir)
- except OSError, (errno, msg):
+ except OSError as msg:
raise CreatorError("Create image by cpio error: %s" % msg)
def copy_cpio_image(self):
'label': label,
'fslabel':fslabel,
'name': imgname,
- 'size': part.size or 4096L * 1024 * 1024,
+ 'size': part.size or 4096 * 1024 * 1024,
'fstype': part.fstype or 'ext3',
'fsopts': part.fsopts or None,
'aft_fstype': aft_fstype or None,
if self.ks:
self.__image_size = kickstart.get_image_size(self.ks,
- 4096L * 1024 * 1024)
+ 4096 * 1024 * 1024)
else:
self.__image_size = 0
"mountpoint": "/",
"label": self.name,
"name": imgname,
- "size": self.__image_size or 4096L,
+ "size": self.__image_size or 4096,
"fstype": self.__fstype or "ext3",
"extopts": None,
"loop": None,
fstype = loop['fstype']
fsopt = loop['fsopts']
mp = os.path.join(self._instroot, loop['mountpoint'].lstrip('/'))
- size = loop['size'] * 1024L * 1024L
+ size = loop['size'] * 1024 * 1024
imgname = loop['name']
if fstype in ("ext2", "ext3", "ext4"):
loop['loop'].uuid:
loop['kspart'].uuid = loop['loop'].uuid
- except MountError, e:
+ except MountError as e:
raise
def _unmount_instroot(self):
% (rootdev, options)
if footlabel == 0:
syslinux_conf += "\tmenu default\n"
- footlabel += 1;
+ footlabel += 1
msger.debug("Writing syslinux config %s/boot/extlinux/extlinux.conf" \
% self._instroot)
if not self.__instloop is None:
try:
self.__instloop.cleanup()
- except MountError, err:
+ except MountError as err:
msger.warning("%s" % err)
def _resparse(self, size = None):
def wrapper(*kargs, **kwargs):
try:
func(*kargs, **kwargs)
- except (OSError, IOError, errors.KsError), err:
+ except (OSError, IOError, errors.KsError) as err:
cfgcls = kargs[0].__class__.__name__
if msger.ask("Failed to apply %s, skip and continue?" % cfgcls):
msger.warning("%s" % err)
try:
ks.readKickstart(path)
- except (kserrors.KickstartParseError, kserrors.KickstartError), err:
+ except (kserrors.KickstartParseError, kserrors.KickstartError) as err:
if msger.ask("Errors occured on kickstart file, skip and continue?"):
msger.warning("%s" % err)
pass
subprocess.call([lncmd, "-s",
self.path(tz_midst),
self.path(tz_dest)])
- except (IOError, OSError), (errno, msg):
+ except (IOError, OSError) as msg:
raise errors.KsError("Timezone setting error: %s" % msg)
class AuthConfig(KickstartConfig):
@apply_wrapper
def apply(self, ksxconfig):
if ksxconfig.startX and os.path.exists(self.path("/etc/inittab")):
- f = open(self.path("/etc/inittab"), "rw+")
+ f = open(self.path("/etc/inittab"), "w+")
buf = f.read()
buf = buf.replace("id:3:initdefault", "id:5:initdefault")
f.seek(0)
p = self.path("/etc/sysconfig/network-scripts/ifcfg-" + network.device)
f = file(p, "w+")
- os.chmod(p, 0644)
+ os.chmod(p, 0o644)
f.write("DEVICE=%s\n" % network.device)
f.write("BOOTPROTO=%s\n" % network.bootProto)
p = self.path("/etc/sysconfig/network-scripts/keys-" + network.device)
f = file(p, "w+")
- os.chmod(p, 0600)
+ os.chmod(p, 0o600)
f.write("KEY=%s\n" % network.wepkey)
f.close()
def write_sysconfig(self, useipv6, hostname, gateway):
path = self.path("/etc/sysconfig/network")
f = file(path, "w+")
- os.chmod(path, 0644)
+ os.chmod(path, 0o644)
f.write("NETWORKING=yes\n")
path = self.path("/etc/hosts")
f = file(path, "w+")
- os.chmod(path, 0644)
+ os.chmod(path, 0o644)
f.write("127.0.0.1\t\t%s\n" % localline)
f.write("::1\t\tlocalhost6.localdomain6 localhost6\n")
f.close()
path = self.path("/etc/resolv.conf")
f = file(path, "w+")
- os.chmod(path, 0644)
+ os.chmod(path, 0o644)
for ns in (nameservers):
if ns:
if p.mountpoint == "/" and p.size:
__size = p.size
if __size > 0:
- return int(__size) * 1024L * 1024L
+ return int(__size) * 1024 * 1024
else:
return default
(opts, extra) = self.op.parse_args(args=args)
if extra:
- m = _("Unexpected arguments to %(command)s command: %(options)s") \
+ m = ("Unexpected arguments to %(command)s command: %(options)s") \
% {"command": "desktop", "options": extra}
- raise KickstartValueError, formatErrorMsg(self.lineno, msg=m)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg=m))
self._setToSelf(self.op, opts)
if len(extra) != 1:
msg = "Kickstart command \"%s\" requires one " \
"argumet - a list of legacy features to disable" % self.currentCmd
- raise KickstartValueError, formatErrorMsg(self.lineno, msg = msg)
+ raise KickstartValueError (formatErrorMsg(self.lineno, msg = msg))
self.features = extra[0].split(",")
self.plugin_dirs[pdir] = True
msger.debug("Plugin module %s:%s imported"\
% (mod, pymod.__file__))
- except ImportError, err:
+ except ImportError as err:
msg = 'Failed to load plugin %s/%s: %s' \
% (os.path.basename(pdir), mod, err)
msger.verbose(msg)
def show_plugins(cls):
for cls in cls.plugins[cls.mic_plugin_type]:
- print cls
+ print (cls)
def get_plugins(cls):
return cls.plugins
# with this program; if not, write to the Free Software Foundation, Inc., 59
# Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-from __future__ import with_statement
import os
import sys
import glob
return (os.stat("/").st_ino != 2)
def bootstrap_mic(argv=None):
-
-
def mychroot():
os.chroot(rootdir)
os.chdir(cwd)
bindmounts = get_bindmounts(cropts)
ret = bsenv.run(argv, cwd, rootdir, bindmounts)
- except errors.BootstrapError, err:
+ except errors.BootstrapError as err:
raise errors.CreatorError("Failed to download/install bootstrap package " \
"or the package is in bad format: %s" % err)
- except RuntimeError, err:
+ except RuntimeError as err:
#change exception type but keep the trace back
- value, tb = sys.exc_info()[1:]
- raise errors.CreatorError, value, tb
+ value,tb = sys.exc_info()[1:]
+ raise errors.CreatorError((value,tb))
else:
sys.exit(ret)
finally:
for key, value in micpaths.items():
try:
safecopy(value, _path(eval(key)), False, ["*.pyc", "*.pyo"])
- except (OSError, IOError), err:
+ except (OSError, IOError) as err:
raise errors.BootstrapError(err)
# auto select backend
wf.write(conf_str)
# chmod +x /usr/bin/mic
- os.chmod(_path(binpth), 0777)
+ os.chmod(_path(binpth), 0o777)
# correct python interpreter
mic_cont = file(_path(binpth)).read()
"""
try:
os.makedirs(dirname)
- except OSError, err:
+ except OSError as err:
if err.errno != errno.EEXIST:
raise
def mkvdfs(in_img, out_img, fsoptions):
""" This function is incomplete. """
fullpathmkvdfs = find_binary_path("mkfs.vdfs")
-# args = fullpathmkvdfs + " -i -r "+ in_img + " -z 1024M -s " + out_img
+# args = fullpathmkvdfs + " -i -r "+ in_img + " -z 1024M -s " + out_img
args = fullpathmkvdfs + " " + fsoptions + " -r " + in_img + " " + out_img
msger.verbose("vdfs args: %s" % args)
runner.show("%s --help" % fullpathmkvdfs)
-# if not sys.stdout.isatty():
+# if not sys.stdout.isatty():
# args.append("-no-progress")
# runner.show("%s --help" % fullpathmkvdfs)
ret = runner.show(args)
try:
makedirs(self.dest)
- except OSError, err:
+ except OSError as err:
if err.errno == errno.ENOSPC:
msger.warning("No space left on device '%s'" % err.filename)
return
msger.debug("Extending sparse file %s to %d" % (self.lofile, size))
if create:
- fd = os.open(self.lofile, flags, 0644)
+ fd = os.open(self.lofile, flags, 0o644)
else:
fd = os.open(self.lofile, flags)
os.ftruncate(fd, size)
except:
# may be limited by 2G in 32bit env
- os.ftruncate(fd, 2**31L)
+ os.ftruncate(fd, 2**31)
os.close(fd)
if self.rmdir and not self.mounted:
try:
os.rmdir(self.mountdir)
- except OSError, e:
+ except OSError as e:
pass
self.rmdir = False
resize2fs(self.disk.lofile, size)
if size and size != os.stat(self.disk.lofile)[stat.ST_SIZE]:
- raise MountError("Failed to resize filesystem %s to " % (self.disk.lofile, size))
+ raise MountError("Failed to resize filesystem %s to %d " % (self.disk.lofile, size))
return size
imgloop = LoopbackDisk(image, None) # Passing bogus size - doesn't matter
cowloop = SparseLoopbackDisk(os.path.join(os.path.dirname(path), "osmin"),
- 64L * 1024L * 1024L)
+ 64 * 1024 * 1024)
snapshot = DeviceMapperSnapshot(imgloop, cowloop)
maxid = 1 + max(filter(lambda x: x<100,
map(fint, glob.glob("/dev/loop[0-9]*"))))
if maxid < 10: maxid = 10
- if maxid >= 100: raise
+ if maxid >= 100:
+ raise
return maxid
def _kpseek(self, device):
try:
self.cleanup()
self.device = None
- except MountError, e:
+ except MountError as e:
raise CreatorError("%s" % e)
def cleanup(self):
DEVICE_LOCKFILE = "/var/lock/__mic_loopdev.lock"
def get_loop_device(losetupcmd, lofile):
- global DEVICE_PIDFILE_DIR
- global DEVICE_LOCKFILE
-
import fcntl
makedirs(os.path.dirname(DEVICE_LOCKFILE))
fp = open(DEVICE_LOCKFILE, 'w')
with open(pidfile, 'w') as wf:
wf.write(str(os.getpid()))
- except MountError, err:
+ except MountError as err:
raise CreatorError("%s" % str(err))
except:
raise
if entry['index'] >= header['entries_cnt']:
raise MountError("Partition table at LBA %d has only %d " \
- "records cannot change record number %d" % \
+ "records cannot change record number " % \
(header['entries_cnt'], entry['index']))
# Read raw GPT header
raw_hdr = self._read_disk(header['hdr_offs'], _GPT_HEADER_SIZE)
http_headers=(('Pragma', 'no-cache'),),
quote=0,
progress_obj=progress_obj)
- except grabber.URLGrabError, err:
+ except grabber.URLGrabError as err:
tmp = SafeURL(url)
msg = str(err)
pass
def unhide_loopdev_presentation():
- global _LOOP_RULE_PTH
+ #global _LOOP_RULE_PTH
if not _LOOP_RULE_PTH:
return
def remove_temp_ks():
try:
os.unlink(ksconf)
- except OSError, err:
+ except OSError as err:
msger.warning('Failed to remove temp ks file:%s:%s' % (ksconf, err))
import atexit
_my_noproxy_list = []
def set_proxy_environ():
- global _my_noproxy, _my_proxies
if not _my_proxies:
return
for key in _my_proxies.keys():
c_result = os.popen(cmd).readlines()
if len(c_result) == 0:
continue
- except Exception,e:
+ except Exception as e:
msger.warning(str(e))
continue
to_list = c_result[0].strip("\n").split(",")
elif what == rpm.RPMCALLBACK_INST_PROGRESS:
if h is not None:
- percent = (self.total_installed*100L)/self.total_actions
+ percent = (self.total_installed*100)/self.total_actions
if total > 0:
try:
hdr, rpmloc = h
try:
hdr = ts.hdrFromFdno(fdno)
- except rpm.error, e:
+ except rpm.error as e:
if str(e) == "public key not availaiable":
value = 1
if str(e) == "public key not available":
(sout, serr) = p.communicate()
# combine stdout and stderr, filter None out
out = ''.join(filter(None, [sout, serr]))
- except OSError, e:
+ except OSError as e:
if e.errno == 2:
# [Errno 2] No such file or directory
raise errors.CreatorError('Cannot run command: %s, lost dependency?' % cmd)
import M2Crypto
m2c_connection = M2Crypto.SSL.Connection.clientPostConnectionCheck
M2Crypto.SSL.Connection.clientPostConnectionCheck = None
- except ImportError, err:
+ except ImportError as err:
raise CreatorError("%s, please try to install python-m2crypto" % str(err))
proxy = None
f.write(conf)
f.close()
- os.chmod(confpath, 0644)
+ os.chmod(confpath, 0o644)
def _cleanupRpmdbLocks(self, installroot):
# cleans up temporary files left by bdb so that differing
return None
except yum.Errors.InstallError:
return "No package(s) available to install"
- except yum.Errors.RepoError, e:
+ except yum.Errors.RepoError as e:
raise CreatorError("Unable to download from repo : %s" % (e,))
- except yum.Errors.YumBaseError, e:
+ except yum.Errors.YumBaseError as e:
raise CreatorError("Unable to install: %s" % (e,))
def deselectPackage(self, pkg):
self.selectPackage(p)
return None
- except (yum.Errors.InstallError, yum.Errors.GroupsError), e:
+ except (yum.Errors.InstallError, yum.Errors.GroupsError) as e:
return e
- except yum.Errors.RepoError, e:
+ except yum.Errors.RepoError as e:
raise CreatorError("Unable to download from repo : %s" % (e,))
- except yum.Errors.YumBaseError, e:
+ except yum.Errors.YumBaseError as e:
raise CreatorError("Unable to install: %s" % (e,))
def addRepository(self, name, url = None, mirrorlist = None, proxy = None,
ts = rpmUtils.transaction.initReadOnlyTransaction()
try:
hdr = rpmUtils.miscutils.hdrFromPackage(ts, pkg)
- except rpmUtils.RpmUtilsError, e:
- raise yum.Errors.MiscError, \
- 'Could not open local rpm file: %s: %s' % (pkg, e)
+ except rpmUtils.RpmUtilsError as e:
+ raise yum.Errors.MiscError \
+ ('Could not open local rpm file: %s: %s' % (pkg, e))
self.deselectPackage(hdr['name'])
yum.YumBase.installLocal(self, pkg, po, updateonly)
os.environ["LD_PRELOAD"] = ""
try:
(res, resmsg) = self.buildTransaction()
- except yum.Errors.RepoError, e:
+ except yum.Errors.RepoError as e:
raise CreatorError("Unable to download from repo : %s" %(e,))
if res != 2:
raise CreatorError("No enough space used for downloading.")
# record the total size of installed pkgs
- pkgs_total_size = 0L
+ pkgs_total_size = 0
for x in dlpkgs:
if hasattr(x, 'installedsize'):
pkgs_total_size += int(x.installedsize)
raise CreatorError("mic failes to install some packages")
self._cleanupRpmdbLocks(self.conf.installroot)
- except rpmUtils.RpmUtilsError, e:
+ except rpmUtils.RpmUtilsError as e:
raise CreatorError("mic does NOT support delta rpm: %s" % e)
- except yum.Errors.RepoError, e:
+ except yum.Errors.RepoError as e:
raise CreatorError("Unable to download from repo : %s" % e)
- except yum.Errors.YumBaseError, e:
+ except yum.Errors.YumBaseError as e:
raise CreatorError("Unable to install: %s" % e)
finally:
msger.disable_logstderr()
}
try:
self.__pkgs_vcsinfo[lname] = hdr['VCS']
- except ValueError, KeyError:
+ except ValueError as KeyError:
self.__pkgs_vcsinfo[lname] = None
return self.__pkgs_vcsinfo
self.__build_repo_cache(name)
- except RuntimeError, e:
+ except RuntimeError as e:
raise CreatorError(str(e))
msger.verbose('repo: %s was added' % name)
if download_count > 0:
msger.info("Downloading packages ...")
self.downloadPkgs(dlpkgs, download_count)
- except CreatorError, e:
+ except CreatorError as e:
raise CreatorError("Package download failed: %s" %(e,))
try:
self.installPkgs(dlpkgs)
except (RepoError, RpmError):
raise
- except Exception, e:
+ except Exception as e:
raise CreatorError("Package installation failed: %s" % (e,))
def getVcsInfo(self):
cmd = creatoropts['run_script']
try:
runner.show(cmd)
- except OSError,err:
+ except OSError as err:
msger.warning(str(err))
cmd = creatoropts['run_script']
try:
runner.show(cmd)
- except OSError,err:
+ except OSError as err:
msger.warning(str(err))
msger.info("Finished.")
raise errors.CreatorError("Cannot support fstype: %s" % fstype)
name = os.path.join(tmpdir, name)
- size = size * 1024L * 1024L
+ size = size * 1024 * 1024
loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
os.path.join(mntdir, mp.lstrip('/')),
fstype, size, label)
raise errors.CreatorError("damaged tarball for loop images")
img = target
- imgsize = misc.get_file_size(img) * 1024L * 1024L
+ imgsize = misc.get_file_size(img) * 1024 * 1024
imgtype = misc.get_image_type(img)
if imgtype == "btrfsimg":
fstype = "btrfs"
cmd = creatoropts['run_script']
try:
runner.show(cmd)
- except OSError,err:
+ except OSError as err:
msger.warning(str(err))
cmd = creatoropts['run_script']
try:
runner.show(cmd)
- except OSError,err:
+ except OSError as err:
msger.warning(str(err))
@classmethod
def do_chroot(cls, target, cmd=[]):
img = target
- imgsize = misc.get_file_size(img) * 1024L * 1024L
+ imgsize = misc.get_file_size(img) * 1024 * 1024
partedcmd = fs_related.find_binary_path("parted")
disk = fs_related.SparseLoopbackDisk(img, imgsize)
imgmnt = misc.mkdtemp()
@classmethod
def do_unpack(cls, srcimg):
- srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
+ srcimgsize = (misc.get_file_size(srcimg)) * 1024 * 1024
srcmnt = misc.mkdtemp("srcmnt")
disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
srcloop = PartitionedMount(srcmnt, skipformat = True)
def testChroot(self):
try:
chroot.chroot(TEST_CHROOT_DIR, None, 'exit')
- except Exception, e:
+ except Exception as e:
raise self.failureException(e)
if __name__ == "__main__":