Ported scripts to Python 3

This commit is contained in:
Tomas Radej 2014-08-01 16:22:04 +02:00
parent 8f52fbc0b1
commit 59bbdc828a
3 changed files with 133 additions and 124 deletions

View File

@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/python3
# $Id$
# Update CUPS PPDs for Gutenprint queues.
# Copyright (C) 2002-2003 Roger Leigh (rleigh@debian.org)
@ -25,6 +25,7 @@ import re
import stat
import subprocess
import sys
from functools import reduce
global optargs
global debug
@ -59,7 +60,7 @@ global ppd_files
global languagemappings
def help():
print """
print("""
Usage: %s [OPTION]... [PPD_FILE]...
Update CUPS+Gutenprint PPD files.
@ -81,7 +82,7 @@ Update CUPS+Gutenprint PPD files.
Or -loriginal to preserve original language
with Gutenprint 5.2 or above
""" % (sys.argv[0],
reduce (lambda x,y: "%s %s" % (x,y), languages))
reduce (lambda x,y: "%s %s" % (x,y), languages)))
sys.exit (0)
def die_if_not_directory (dir):
@ -89,8 +90,9 @@ def die_if_not_directory (dir):
st = os.stat (dir)
if not stat.S_ISDIR (st.st_mode):
os.chdir (dir)
except OSError, (e, s):
print "%s: invalid directory: %s" % (dir, s)
except OSError as err:
(e, s) = err.args
print("%s: invalid directory: %s" % (dir, s))
sys.exit (1)
def get_driver_version():
@ -154,36 +156,36 @@ def parse_options():
for opt, optarg in opts:
optargs[opt[1]] = optarg
if optargs.has_key ('n'):
if 'n' in optargs:
no_action = 1
if optargs.has_key ('d'):
if 'd' in optargs:
try:
debug = int (optargs['d'])
except ValueError:
d = 0
if optargs.has_key ('v'):
if 'v' in optargs:
verbose = 1
quiet = 0
if optargs.has_key ('q'):
if 'q' in optargs:
verbose = 0
quiet = 1
if optargs.has_key ('N'):
if 'N' in optargs:
reset_defaults = 1
if optargs.has_key ('o'):
if 'o' in optargs:
opt_o = optargs['o']
die_if_not_directory (opt_o)
ppd_out_dir = opt_o
if optargs.has_key ('r'):
if 'r' in optargs:
opt_r = optargs['r']
if version != opt_r:
version = opt_r
if optargs.has_key ('s'):
if 's' in optargs:
opt_s = optargs['s']
die_if_not_directory (opt_s)
ppd_base_dir = opt_s
@ -203,10 +205,10 @@ def parse_options():
use_static_ppd = "no"
file_version = "\"%s\"$" % driver_version
else:
print "Gutenprint %s does not appear to be installed!" % version
print("Gutenprint %s does not appear to be installed!" % version)
sys.exit (1)
if optargs.has_key ('s'):
if 's' in optargs:
opt_s = optargs['s']
die_if_not_directory (opt_s)
ppd_base_dir = opt_s
@ -215,36 +217,36 @@ def parse_options():
driver_version = ""
use_static_ppd = "yes"
if optargs.has_key ('p'):
if 'p' in optargs:
opt_p = optargs['p']
die_if_not_directory (opt_p)
ppd_dir = opt_p
if optargs.has_key ('P'):
if 'P' in optargs:
opt_P = optargs['P']
if os.access (opt_P, os.X_OK):
driver_bin = opt_P
get_driver_version ()
use_static_ppd = "no"
else:
print "%s: invalid executable" % opt_P
print("%s: invalid executable" % opt_P)
if optargs.has_key ('h'):
if 'h' in optargs:
help ()
if (optargs.has_key ('l') and
if ('l' in optargs and
optargs['l'].lower () != "original" and
optargs['l'].lower () not in languages):
print >>sys.stderr, "Unknown language '%s'" % optargs['l']
print("Unknown language '%s'" % optargs['l'], file=sys.stderr)
if optargs.has_key ('i'):
if 'i' in optargs:
interactive = 1
if exit_after_parse_args:
sys.exit (0)
if verbose and driver_version != "":
print "Updating PPD files from Gutenprint %s" % driver_version
print("Updating PPD files from Gutenprint %s" % driver_version)
return args
@ -267,7 +269,7 @@ def update_ppd (ppd_source_filename):
orig = file (ppd_source_filename)
orig_metadata = os.fstat (orig.fileno ())
if debug & 1:
print "Source Filename: %s" % ppd_source_filename
print("Source Filename: %s" % ppd_source_filename)
filename = ""
driver = ""
@ -327,21 +329,21 @@ def update_ppd (ppd_source_filename):
# ppd_source_filename)
return -1
if (optargs.has_key ('l') and
if ('l' in optargs and
optargs['l'] != "" and
optargs['l'].lower () != "original"):
locale = optargs['l']
orig_locale = locale
if debug & 2:
print "Gutenprint Filename: %s" % filename
if optargs.has_key ('l'):
print "Locale: %s (from -l)" % locale
print("Gutenprint Filename: %s" % filename)
if 'l' in optargs:
print("Locale: %s (from -l)" % locale)
else:
print "Locale: %s" % locale
print("Locale: %s" % locale)
print "Language: %s" % lingo
print "Driver: %s" % driver
print("Language: %s" % lingo)
print("Driver: %s" % driver)
if locale:
# Split into the language and territory.
@ -364,8 +366,8 @@ def update_ppd (ppd_source_filename):
locale = languagemappings.get (lingo.lower (), "C")
if debug & 2:
print "Base Locale: %s" % locale
print "Region: %s" % region
print("Base Locale: %s" % locale)
print("Region: %s" % region)
# Read in the new PPD, decompressing it if needed...
(new_ppd_filename, source_fd) = get_ppd_fh (ppd_source_filename,
@ -374,23 +376,23 @@ def update_ppd (ppd_source_filename):
locale,
region)
if source_fd == None:
print "Unable to retrieve PPD file!"
print("Unable to retrieve PPD file!")
return 0
if interactive:
inp = raw_input ("Update PPD %s from %s [nyq]? " % ppd_source_filename)
inp = input ("Update PPD %s from %s [nyq]? " % ppd_source_filename)
inp = inp.lower ()
if inp.startswith ("q"):
if not server_multicat:
source_fd.close ()
print "Skipping all..."
print("Skipping all...")
return -2
elif not inp.startswith ("y"):
if not server_multicat:
source_fd.close ()
print "Skipping..."
print("Skipping...")
return -1
# Extract the default values from the original PPD...
@ -413,7 +415,7 @@ def update_ppd (ppd_source_filename):
options = nopt
resolution_map = nres
old_resolution_map = dict()
for key, value in resolution_map.iteritems ():
for key, value in resolution_map.items ():
old_resolution_map[value] = key
# Store previous language in the PPD file so that -l original works
@ -431,8 +433,8 @@ def update_ppd (ppd_source_filename):
source_data += line + "\n"
if debug & 4:
print "Options (Old->New Default Type):"
keys = options.keys ()
print("Options (Old->New Default Type):")
keys = list(options.keys ())
keys.sort ()
for t in keys:
old_type = orig_default_types.get (t, "(New)")
@ -449,48 +451,48 @@ def update_ppd (ppd_source_filename):
out += "%s " % opt
print out
print(out)
if len (resolution_map.keys ()) > 0:
print "Resolution Map:"
keys = resolution_map.keys ()
if len (list(resolution_map.keys ())) > 0:
print("Resolution Map:")
keys = list(resolution_map.keys ())
keys.sort ()
for key in keys:
print " %s: %s" % (key, resolution_map[key])
print(" %s: %s" % (key, resolution_map[key]))
if len (old_resolution_map.keys ()) > 0:
print "Old Resolution Map:"
keys = old_resolution_map.keys ()
if len (list(old_resolution_map.keys ())) > 0:
print("Old Resolution Map:")
keys = list(old_resolution_map.keys ())
keys.sort ()
for key in keys:
print " %s: %s" % (key, old_resolution_map[key])
print(" %s: %s" % (key, old_resolution_map[key]))
print "Non-UI Defaults:"
keys = defaults.keys ()
print("Non-UI Defaults:")
keys = list(defaults.keys ())
keys.sort ()
for key in keys:
xkey = key
if xkey.startswith ("Default"):
xkey = xkey[7:]
if not options.has_key (xkey):
print " %s: %s" % (key, defaults[key])
if xkey not in options:
print(" %s: %s" % (key, defaults[key]))
print "Default Types of dropped options:"
keys = orig_default_types.keys ()
print("Default Types of dropped options:")
keys = list(orig_default_types.keys ())
keys.sort ()
for t in keys:
if not options.has_key (t):
print " %s: %s" % (t, orig_default_types[t])
if t not in options:
print(" %s: %s" % (t, orig_default_types[t]))
if no_action:
if not quiet or verbose:
if ppd_dest_filename == ppd_source_filename:
print "Would update %s using %s" % (ppd_source_filename,
new_ppd_filename)
print("Would update %s using %s" % (ppd_source_filename,
new_ppd_filename))
else:
print "Would update %s to %s using %s" % (ppd_source_filename,
print("Would update %s to %s using %s" % (ppd_source_filename,
ppd_dest_filename,
new_ppd_filename)
new_ppd_filename))
return 0
@ -498,7 +500,7 @@ def update_ppd (ppd_source_filename):
# Update source buffer with old defaults...
# Loop through each default in turn.
keys = defaults.keys ()
keys = list(defaults.keys ())
keys.sort ()
for default_option in keys:
default_option_value = defaults[default_option]
@ -518,9 +520,9 @@ def update_ppd (ppd_source_filename):
if (new_default != None and
default_option_value == new_default):
if verbose:
print "%s: Preserve *%s (%s)" % (ppd_source_filename,
print("%s: Preserve *%s (%s)" % (ppd_source_filename,
default_option,
default_option_value)
default_option_value))
continue
@ -532,10 +534,10 @@ def update_ppd (ppd_source_filename):
def_option = default_option_value
odef_option = def_option
if (option == "Resolution" and
old_resolution_map.has_key (def_option)):
def_option in old_resolution_map):
if debug & 4:
print ("Intermapping old resolution %s to %s" %
def_option, old_resolution_map[def_option])
print(("Intermapping old resolution %s to %s" %
def_option, old_resolution_map[def_option]))
def_option = old_resolution_map[def_option]
@ -548,7 +550,7 @@ def update_ppd (ppd_source_filename):
if dopt == opt:
valid = True
elif (option == "Resolution" and
resolution_map.has_key (dopt)):
dopt in resolution_map):
dopt = resolution_map[dopt]
if dopt == opt:
valid = True
@ -567,9 +569,9 @@ def update_ppd (ppd_source_filename):
source_data += line + "\n"
if verbose:
print "%s: Set *%s to %s" % (ppd_source_filename,
print("%s: Set *%s to %s" % (ppd_source_filename,
default_option,
dopt)
dopt))
next_default = True
break
@ -579,28 +581,30 @@ def update_ppd (ppd_source_filename):
if next_default:
continue
print ("Warning: %s: Invalid option: *%s: %s. Using default "
print(("Warning: %s: Invalid option: *%s: %s. Using default "
"setting %s." % (ppd_source_filename, default_option,
defaults[default_option],
new_defaults[default_option]))
new_defaults[default_option])))
continue
print ("Warning: %s: PPD OpenUI method %s not understood." %
(ppd_source_filename, new_default_types[default_option]))
print(("Warning: %s: PPD OpenUI method %s not understood." %
(ppd_source_filename, new_default_types[default_option])))
# Write new PPD...
tmpnew = "%s.new" % ppd_dest_filename
try:
newppd = file (tmpnew, "w")
except IOError, (e, s):
print "Can't create %s: %s" % (tmpnew, s)
except IOError as err:
(e, s) = err.args
print("Can't create %s: %s" % (tmpnew, s))
return 0
newppd.writelines (source_data)
try:
newppd.close ()
except IOError, (e, s):
print "Can't write to %s: %s" % (tmpnew, s)
except IOError as err:
(e, s) = err.args
print("Can't write to %s: %s" % (tmpnew, s))
return 0
chcon = subprocess.Popen (["chcon", "--reference=%s" % ppd_dest_filename,
@ -612,8 +616,9 @@ def update_ppd (ppd_source_filename):
try:
os.rename (tmpnew, ppd_dest_filename)
except OSError, (e, s):
print "Can't rename %s to %s: %s" % (tmpnew, ppd_dest_filename, s)
except OSError as err:
(e, s) = err.args
print("Can't rename %s to %s: %s" % (tmpnew, ppd_dest_filename, s))
try:
os.unlink (tmpnew)
except OSError:
@ -630,18 +635,18 @@ def update_ppd (ppd_source_filename):
try:
os.chmod (ppd_dest_filename,
orig_metadata.st_mode & 0777)
orig_metadata.st_mode & 0o777)
except OSError:
pass
if not quiet or verbose:
if ppd_dest_filename == ppd_source_filename:
print "Updated %s using %s" % (ppd_source_filename,
new_ppd_filename)
print("Updated %s using %s" % (ppd_source_filename,
new_ppd_filename))
else:
print "Updated %s to %s using %s" % (ppd_source_filename,
print("Updated %s to %s using %s" % (ppd_source_filename,
ppd_dest_filename,
new_ppd_filename)
new_ppd_filename))
# All done!
return 1
@ -734,7 +739,7 @@ def get_ppd_fh (ppd_source_filename, filename, driver, locale, region):
url_list = []
if (((opt_r != None and opt_r < 5.2) or
(optargs.has_key ('l') and optargs['l'] != "")) and
('l' in optargs and optargs['l'] != "")) and
locale != ""):
if region:
url_list.append ("gutenprint.%s://%s/%s/%s_%s" %
@ -752,8 +757,8 @@ def get_ppd_fh (ppd_source_filename, filename, driver, locale, region):
else:
cat = "%s cat " % driver_bin
print ("Trying %s%s for %s, %s, %s, %s" %
(cat, url, driver, simplified, locale, region))
print(("Trying %s%s for %s, %s, %s, %s" %
(cat, url, driver, simplified, locale, region)))
if server_multicat:
try:
@ -767,7 +772,7 @@ def get_ppd_fh (ppd_source_filename, filename, driver, locale, region):
"w"))
server_multicat_initialized = mc_proc
print >>server_multicat_initialized.stdin, "%s" % url
print("%s" % url, file=server_multicat_initialized.stdin)
server_multicat_initialized.stdin.flush ()
return (new_ppd_filename,
server_multicat_initialized.stdout)
@ -791,14 +796,14 @@ def get_ppd_fh (ppd_source_filename, filename, driver, locale, region):
new_ppd_filename = find_ppd (filename, driver, locale, region)
if not new_ppd_filename:
# There wasn't a valid source PPD file, so give up.
print >>sys.stderr, ("%s: no valid candidate for replacement. "
"Skipping" % ppd_source_filename)
print >>sys.stderr, ("%s: please upgrade this PPD manually" %
ppd_source_filename)
print(("%s: no valid candidate for replacement. "
"Skipping" % ppd_source_filename), file=sys.stderr)
print(("%s: please upgrade this PPD manually" %
ppd_source_filename), file=sys.stderr)
return ("", None)
if debug & 1:
print "Candidate PPD: %s" % new_ppd_filename
print("Candidate PPD: %s" % new_ppd_filename)
suffix = "\\" + gzext # Add '\' so the regexp matches the '.'
if new_ppd_filename.endswith (".gz"):
@ -809,8 +814,9 @@ def get_ppd_fh (ppd_source_filename, filename, driver, locale, region):
stdin=file("/dev/null"),
stdout=subprocess.PIPE,
stderr=file("/dev/null", "w"))
except OSError, (e, s):
print "can't open for decompression: %s" % s
except OSError as err:
(e, s) = err.args
print("can't open for decompression: %s" % s)
sys.exit (1)
return (new_ppd_filename, proc.stdout)
@ -840,7 +846,7 @@ def find_ppd (gutenprintfilename, drivername, lang, region):
current_best_file = ""
current_best_time = 0
if optargs.has_key ('s'):
if 's' in optargs:
basedirs = [optargs['s']]
else:
basedirs = [ppd_base_dir, stored_dir, ppd_root_dir]
@ -874,15 +880,15 @@ def find_ppd (gutenprintfilename, drivername, lang, region):
fn = "%s/%s%s%s" % (basedir, lingo, base, suffix)
if debug & 8:
print ("Trying %s for %s, %s, %s" %
(fn, gutenprintfilename, lang, region))
print(("Trying %s for %s, %s, %s" %
(fn, gutenprintfilename, lang, region)))
try:
st = os.stat (fn)
except OSError:
continue
if (optargs.has_key ('f') or
if ('f' in optargs or
(stat.S_ISREG (st.st_mode) and
st.st_uid == 0)):
# Check that the file is a valid Gutenprint PPD file
@ -905,25 +911,25 @@ def find_ppd (gutenprintfilename, drivername, lang, region):
if new_file_version != "":
if debug & 8:
print (" Format valid: time %s best %s "
print((" Format valid: time %s best %s "
"prev %s cur %s!" %
(st.st_mtime, current_best_time,
current_best_file, fn))
current_best_file, fn)))
if st.st_mtime > current_best_time:
current_best_time = st.st_mtime
current_best_file = fn
if debug & 8:
print >>sys.stderr, ("***current_best_file "
" is %s" % fn)
print(("***current_best_file "
" is %s" % fn), file=sys.stderr)
elif debug & 8:
print " Format invalid"
print(" Format invalid")
else:
if (not stat.S_ISDIR (st.st_mode) and
not fn.endswith ("/")):
print >>sys.stderr, ("%s: not a regular file, "
print(("%s: not a regular file, "
"or insecure ownership and "
"permissions. Skipped" % fn)
"permissions. Skipped" % fn), file=sys.stderr)
if current_best_file:
return current_best_file
@ -987,7 +993,7 @@ languagemappings = { "chinese": "cn",
args = parse_options()
# Set a secure umask...
os.umask (0177)
os.umask (0o177)
# Find all in-use Gutenprint PPD files...
@ -1006,8 +1012,8 @@ for f in args:
elif os.access ("%s/%s.PPD" % (ppd_dir, f), os.F_OK):
ppd_files.append ("%s/%s.PPD" % (ppd_dir, f))
else:
print >>sys.stderr, ("Cannot find file %s/%s, %s/%s.ppd, or %s/%s.PPD" %
ppd_dir, f, ppd_dir, f, ppd_dir, f)
print(("Cannot find file %s/%s, %s/%s.ppd, or %s/%s.PPD" %
ppd_dir, f, ppd_dir, f, ppd_dir, f), file=sys.stderr)
if len (args) == 0:
ppdtmp = glob.glob ("%s/*.ppd" % ppd_dir)
@ -1019,7 +1025,7 @@ if len (args) == 0:
for f in ppdtmp:
if f.endswith (".PPD"):
g = f[:-4] + ".ppd"
if not ppd_map.has_key (g):
if g not in ppd_map:
ppd_files.append (f)
else:
ppd_files.append (f)
@ -1039,20 +1045,20 @@ for ppd_file in ppd_files:
if (not quiet) or verbose:
if len (ppd_files) == 0:
print "No Gutenprint PPD files to update."
print("No Gutenprint PPD files to update.")
elif updated_ppd_count > 0:
plural = ""
if updated_ppd_count != 1:
plural = "s"
print "Updated %d PPD file%s" % (updated_ppd_count, plural)
if ((not optargs.has_key ('o')) or
print("Updated %d PPD file%s" % (updated_ppd_count, plural))
if (('o' not in optargs) or
optargs['o'] != ""):
print "Restart cupsd for the changes to take effect."
print("Restart cupsd for the changes to take effect.")
else:
if failed_ppd_count > 0:
print "Failed to update any PPD files"
print("Failed to update any PPD files")
else:
print "Did not update any PPD files"
print("Did not update any PPD files")
sys.exit (failed_ppd_count > 0)

View File

@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/python3
## gutenprint-foomaticppdupdate
@ -31,7 +31,7 @@ import tempfile
import cups
if len (sys.argv) < 2 or sys.argv[1] == "--help":
print "Usage: gutenprint-foomaticppdupdate <version>"
print("Usage: gutenprint-foomaticppdupdate <version>")
sys.exit (1)
gutenprint_version = sys.argv[1]
@ -46,8 +46,8 @@ def generate_ppd (ppdfile, printer, driver):
fname = ppdfile + ".tmp"
try:
file(fname, "w").write (ppd)
except IOError, e:
print e
except IOError as e:
print(e)
raise
ppdobj = cups.PPD (fname)
@ -67,7 +67,7 @@ def update_ppdfile (ppdfile):
IDs = attr.value.split (" ")
if len (IDs) != 2:
print "Don't understand FoomaticIDs: %s" % IDs
print("Don't understand FoomaticIDs: %s" % IDs)
return
if not IDs[1].startswith ("gutenprint"):
@ -130,7 +130,7 @@ def update_ppdfile (ppdfile):
f = file (ppdfile, "w")
genppd.writeFd (f.fileno ())
print "Updated PPD file %s" % ppdfile
print("Updated PPD file %s" % ppdfile)
for ppdfile in glob.glob ("/etc/cups/ppd/*.ppd"):
update_ppdfile (ppdfile)

View File

@ -3,7 +3,7 @@
Name: gutenprint
Summary: Printer Drivers Package
Version: 5.2.10
Release: 4%{?dist}
Release: 5%{?dist}
URL: http://gimp-print.sourceforge.net/
Source0: http://downloads.sourceforge.net/gimp-print/%{name}-%{version}.tar.bz2
# Post-install script to update foomatic PPDs.
@ -281,6 +281,9 @@ fi
/bin/rm -f /var/cache/foomatic/*
%changelog
* Tue Aug 12 2014 Tomas Radej <tradej@redhat.com> - 5.2.10-5
- Ported scripts to Python 3
* Tue Aug 5 2014 Tim Waugh <twaugh@redhat.com> - 5.2.10-4
- Supply man page for gutenprint-foomaticupdate.
- Link to cups-genppd(8) man page from cups-genppd.5.2(8).