Run 2to3 and pick the sensible suggestions.
Import print_function and absolute_import so 2.6 can work.
There has never been a curses.wrapper module according to 2.x and 3.x
doc, only a function, so "import curses.wrapper" is not correct. It
happened to work because 2.x implemented a (undocumented) module.
We only need to import curses to make curses.wrapper available to
pygrub.
Signed-off-by: Wei Liu <wei.liu2@citrix.com>
Reviewed-by: Andrew Cooper <andrew.cooper3@citrix.com>
# along with this program; If not, see <http://www.gnu.org/licenses/>.
#
+from __future__ import print_function, absolute_import
+
import sys, re, os
import logging
-import GrubConf
+from . import GrubConf
class ExtLinuxImage(object):
def __init__(self, lines, path):
self.lines = []
self.path = path
self.root = ""
- map(self.set_from_line, lines)
+ for line in lines:
+ self.set_from_line(line)
def set_from_line(self, line, replace = None):
(com, arg) = GrubConf.grub_exact_split(line, 2)
setattr(self, "initrd", a.replace("initrd=", ""))
arg = arg.replace(a, "")
- if com is not None and self.commands.has_key(com):
+ if com is not None and com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], re.sub('^"(.+)"$', r"\1", arg.strip()))
else:
def parse(self, buf = None):
if buf is None:
if self.filename is None:
- raise ValueError, "No config file defined to parse!"
+ raise ValueError("No config file defined to parse!")
f = open(self.filename, 'r')
lines = f.readlines()
(com, arg) = GrubConf.grub_exact_split(l, 2)
com = com.lower()
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
if __name__ == "__main__":
if len(sys.argv) < 2:
- raise RuntimeError, "Need a configuration file to read"
+ raise RuntimeError("Need a configuration file to read")
g = ExtLinuxConfigFile(sys.argv[1])
for i in g.images:
- print i
- print g.default
+ print(i)
+ print(g.default)
# along with this program; If not, see <http://www.gnu.org/licenses/>.
#
+from __future__ import print_function, absolute_import
+
import os, sys
import logging
import re
return (None, s)
idx = s.find(')')
if idx == -1:
- raise ValueError, "Unable to find matching ')'"
+ raise ValueError("Unable to find matching ')'")
d = s[:idx]
return (GrubDiskPart(d), s[idx + 1:])
" initrd: %s\n" %(self.title, self.root, self.kernel,
self.args, self.initrd))
def _parse(self, lines):
- map(self.set_from_line, lines)
+ for line in lines:
+ self.set_from_line(line)
def reset(self, lines):
self._root = self._initrd = self._kernel = self._args = None
def set_from_line(self, line, replace = None):
(com, arg) = grub_exact_split(line, 2)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
self.parse()
def parse(self, buf = None):
- raise RuntimeError, "unimplemented parse function"
+ raise RuntimeError("unimplemented parse function")
def hasPasswordAccess(self):
return self.passwordAccess
import crypt
if crypt.crypt(password, pwd[1]) == pwd[1]:
return True
- except Exception, e:
+ except Exception as e:
self.passExc = "Can't verify password: %s" % str(e)
return False
def set(self, line):
(com, arg) = grub_exact_split(line, 2)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
self._default = val
if self._default < 0:
- raise ValueError, "default must be positive number"
+ raise ValueError("default must be positive number")
default = property(_get_default, _set_default)
def set_splash(self, val):
def parse(self, buf = None):
if buf is None:
if self.filename is None:
- raise ValueError, "No config file defined to parse!"
+ raise ValueError("No config file defined to parse!")
f = open(self.filename, 'r')
lines = f.readlines()
continue
(com, arg) = grub_exact_split(l, 2)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
if com == "set":
(com,arg) = grub2_handle_set(arg)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
def parse(self, buf = None):
if buf is None:
if self.filename is None:
- raise ValueError, "No config file defined to parse!"
+ raise ValueError("No config file defined to parse!")
f = open(self.filename, 'r')
lines = f.readlines()
title_match = re.match('^menuentry ["\'](.*?)["\'] (.*){', l)
if title_match:
if img is not None:
- raise RuntimeError, "syntax error: cannot nest menuentry (%d %s)" % (len(img),img)
+ raise RuntimeError("syntax error: cannot nest menuentry (%d %s)" % (len(img),img))
img = []
title = title_match.group(1)
continue
menu_level -= 1
continue
else:
- raise RuntimeError, "syntax error: closing brace without menuentry"
+ raise RuntimeError("syntax error: closing brace without menuentry")
self.add_image(Grub2Image(title, img))
img = None
if com == "set":
(com,arg) = grub2_handle_set(arg)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
arg_strip = arg.strip()
if arg_strip == "${saved_entry}" or arg_strip == "${next_entry}":
logging.warning("Unknown directive %s" %(com,))
if img is not None:
- raise RuntimeError, "syntax error: end of file with open menuentry(%d %s)" % (len(img),img)
+ raise RuntimeError("syntax error: end of file with open menuentry(%d %s)" % (len(img),img))
if self.hasPassword():
self.setPasswordAccess(False)
if __name__ == "__main__":
if len(sys.argv) < 3:
- raise RuntimeError, "Need a grub version (\"grub\" or \"grub2\") and a grub.conf or grub.cfg to read"
+ raise RuntimeError('Need a grub version ("grub" or "grub2") and a grub.conf or grub.cfg to read')
if sys.argv[1] == "grub":
g = GrubConfigFile(sys.argv[2])
elif sys.argv[1] == "grub2":
g = Grub2ConfigFile(sys.argv[2])
else:
- raise RuntimeError, "Unknown config type %s" % sys.argv[1]
+ raise RuntimeError("Unknown config type %s" % sys.argv[1])
for i in g.images:
- print i #, i.title, i.root, i.kernel, i.args, i.initrd
+ print(i) #, i.title, i.root, i.kernel, i.args, i.initrd
#LiloConf.py
#
+from __future__ import print_function, absolute_import
+
import sys, re, os
import logging
-import GrubConf
+from . import GrubConf
class LiloImage(object):
def __init__(self, lines, path):
self.lines = []
self.path = path
self.root = ""
- map(self.set_from_line, lines)
+ for line in lines:
+ self.set_from_line(line)
def set_from_line(self, line, replace = None):
(com, arg) = GrubConf.grub_exact_split(line, 2)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], re.sub('^"(.+)"$', r"\1", arg.strip()))
else:
def parse(self, buf = None):
if buf is None:
if self.filename is None:
- raise ValueError, "No config file defined to parse!"
+ raise ValueError("No config file defined to parse!")
f = open(self.filename, 'r')
lines = f.readlines()
continue
(com, arg) = GrubConf.grub_exact_split(l, 2)
- if self.commands.has_key(com):
+ if com in self.commands:
if self.commands[com] is not None:
setattr(self, self.commands[com], arg.strip())
else:
if __name__ == "__main__":
if len(sys.argv) < 2:
- raise RuntimeError, "Need a lilo.conf to read"
+ raise RuntimeError("Need a lilo.conf to read")
g = LiloConfigFile(sys.argv[1])
for i in g.images:
- print i #, i.title, i.root, i.kernel, i.args, i.initrd
- print g.default
+ print(i) #, i.title, i.root, i.kernel, i.args, i.initrd
+ print(g.default)
# along with this program; If not, see <http://www.gnu.org/licenses/>.
#
+from __future__ import print_function
+
import os, sys, string, struct, tempfile, re, traceback, stat, errno
import copy
import logging
import platform
import xen.lowlevel.xc
-import curses, _curses, curses.wrapper, curses.textpad, curses.ascii
+import curses, _curses, curses.textpad, curses.ascii
import getopt
import xenfsimage
buf = os.read(fd, 512)
os.close(fd)
if struct.unpack("<H", buf[508:510])[0] != DKL_MAGIC:
- raise RuntimeError, "Invalid disklabel magic"
+ raise RuntimeError("Invalid disklabel magic")
nslices = struct.unpack("<H", buf[30:32])[0]
if slicetag == V_ROOT:
return slicesect * SECTOR_SIZE
- raise RuntimeError, "No root slice found"
+ raise RuntimeError("No root slice found")
def get_fs_offset_gpt(file):
fd = os.open(file, os.O_RDONLY)
we're being given a raw config file rather than a disk image."""
if not os.access(fn, os.R_OK):
- raise RuntimeError, "Unable to access %s" %(fn,)
+ raise RuntimeError("Unable to access %s" %(fn,))
- cfg_list = map(lambda x: (x,grub.GrubConf.Grub2ConfigFile),
- ["/boot/grub/grub.cfg", "/grub/grub.cfg",
- "/boot/grub2/grub.cfg", "/grub2/grub.cfg"]) + \
- map(lambda x: (x,grub.ExtLinuxConf.ExtLinuxConfigFile),
- ["/boot/isolinux/isolinux.cfg",
+ cfg_list = [(x,grub.GrubConf.Grub2ConfigFile) for x in ["/boot/grub/grub.cfg", "/grub/grub.cfg",
+ "/boot/grub2/grub.cfg", "/grub2/grub.cfg"]] + \
+ [(x,grub.ExtLinuxConf.ExtLinuxConfigFile) for x in ["/boot/isolinux/isolinux.cfg",
"/boot/extlinux/extlinux.conf",
"/boot/extlinux.conf",
"/extlinux/extlinux.conf",
- "/extlinux.conf"]) + \
- map(lambda x: (x,grub.GrubConf.GrubConfigFile),
- ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
- "/grub/menu.lst", "/grub/grub.conf"])
+ "/extlinux.conf"]] + \
+ [(x,grub.GrubConf.GrubConfigFile) for x in ["/boot/grub/menu.lst", "/boot/grub/grub.conf",
+ "/grub/menu.lst", "/grub/grub.conf"]]
if not fs:
# set the config file and parse it
for f,parser in cfg_list:
if fs.file_exists(f):
- print >>sys.stderr, "Using %s to parse %s" % (parser,f)
+ print("Using %s to parse %s" % (parser,f), file=sys.stderr)
self.cf = parser()
self.cf.filename = f
break
if self.__dict__.get('cf', None) is None:
- raise RuntimeError, "couldn't find bootloader config file in the image provided."
+ raise RuntimeError("couldn't find bootloader config file in the image provided.")
f = fs.open_file(self.cf.filename)
# limit read size to avoid pathological cases
buf = f.read(FS_READ_MAX)
if list_entries:
for i in range(len(g.cf.images)):
img = g.cf.images[i]
- print "title: %s" % img.title
- print " root: %s" % img.root
- print " kernel: %s" % img.kernel[1]
- print " args: %s" % img.args
- print " initrd: %s" % img.initrd[1]
+ print("title: %s" % img.title)
+ print(" root: %s" % img.root)
+ print(" kernel: %s" % img.kernel[1])
+ print(" args: %s" % img.args)
+ print(" initrd: %s" % img.initrd[1])
if interactive and not list_entries:
curses.wrapper(run_main)
sel = idx
if sel == -1:
- print "No kernel image selected!"
+ print("No kernel image selected!")
sys.exit(1)
try:
def format_simple(kernel, ramdisk, args, sep):
for check in (kernel, ramdisk, args):
if check is not None and sep in check:
- raise RuntimeError, "simple format cannot represent delimiter-containing value"
+ raise RuntimeError("simple format cannot represent delimiter-containing value")
s = ("kernel %s" % kernel) + sep
if ramdisk:
s += ("ramdisk %s" % ramdisk) + sep
sel = None
def usage():
- print >> sys.stderr, "Usage: %s [-q|--quiet] [-i|--interactive] [-l|--list-entries] [-n|--not-really] [--output=] [--kernel=] [--ramdisk=] [--args=] [--entry=] [--output-directory=] [--output-format=sxp|simple|simple0] [--offset=] <image>" %(sys.argv[0],)
+ print("Usage: %s [-q|--quiet] [-i|--interactive] [-l|--list-entries] [-n|--not-really] [--output=] [--kernel=] [--ramdisk=] [--args=] [--entry=] [--output-directory=] [--output-format=sxp|simple|simple0] [--offset=] <image>" %(sys.argv[0],), file=sys.stderr)
def copy_from_image(fs, file_to_read, file_type, output_directory,
not_really):
sys.exit("The requested %s file does not exist" % file_type)
try:
datafile = fs.open_file(file_to_read)
- except Exception, e:
- print >>sys.stderr, e
+ except Exception as e:
+ print(e, file=sys.stderr)
sys.exit("Error opening %s in guest" % file_to_read)
(tfd, ret) = tempfile.mkstemp(prefix="boot_"+file_type+".",
dir=output_directory)
return ret
try:
os.write(tfd, data)
- except Exception, e:
- print >>sys.stderr, e
+ except Exception as e:
+ print(e, file=sys.stderr)
os.close(tfd)
os.unlink(ret)
del datafile
try:
part_offs = [ int(a) ]
except ValueError:
- print "offset value must be an integer"
+ print("offset value must be an integer")
usage()
sys.exit(1)
elif o in ("--entry",):
debug = True
elif o in ("--output-format",):
if a not in ["sxp", "simple", "simple0"]:
- print "unknown output format %s" % a
+ print("unknown output format %s" % a)
usage()
sys.exit(1)
output_format = a
elif o in ("--output-directory",):
if not os.path.isdir(a):
- print "%s is not an existing directory" % a
+ print("%s is not an existing directory" % a)
sys.exit(1)
output_directory = a
try:
- os.makedirs(output_directory, 0700)
- except OSError,e:
+ os.makedirs(output_directory, 0o700)
+ except OSError as e:
if (e.errno == errno.EEXIST) and os.path.isdir(output_directory):
pass
else:
# debug
if isconfig:
chosencfg = run_grub(file, entry, fs, incfg["args"])
- print " kernel: %s" % chosencfg["kernel"]
+ print(" kernel: %s" % chosencfg["kernel"])
if chosencfg["ramdisk"]:
- print " initrd: %s" % chosencfg["ramdisk"]
- print " args: %s" % chosencfg["args"]
+ print(" initrd: %s" % chosencfg["ramdisk"])
+ print(" args: %s" % chosencfg["args"])
sys.exit(0)
# if boot filesystem is set then pass to fsimage.open
# Did looping through partitions find us a kernel?
if fs is None:
- raise RuntimeError, "Unable to find partition containing kernel"
+ raise RuntimeError("Unable to find partition containing kernel")
bootcfg["kernel"] = copy_from_image(fs, chosencfg["kernel"], "kernel",
output_directory, not_really)