[python-debian/master 07/36] Use Python 3-style print function in examples.
Colin Watson
cjwatson at canonical.com
Mon Oct 8 07:41:25 UTC 2012
---
examples/changelog/changelog_to_file | 4 ++-
examples/changelog/simple_changelog | 4 ++-
examples/deb822/depgraph | 12 +++++---
examples/deb822/grep-maintainer | 8 +++--
examples/deb822/grep_native_packages.py | 4 ++-
examples/deb822/render-dctrl | 36 ++++++++++++++------------
examples/debfile/ar | 10 ++++---
examples/debfile/changelog_head | 8 +++--
examples/debfile/dpkg-info | 18 +++++++------
examples/debfile/extract_cron | 6 +++-
examples/debtags/pkgwalk | 6 +++-
examples/debtags/reverse | 4 ++-
examples/debtags/smartsearch | 42 ++++++++++++++++--------------
examples/debtags/tagminer | 14 ++++++----
examples/debtags/tagsbyrelevance | 8 +++--
examples/debtags/wxssearch | 12 +++++---
16 files changed, 114 insertions(+), 82 deletions(-)
diff --git a/examples/changelog/changelog_to_file b/examples/changelog/changelog_to_file
index 03ab4a9..7cbcd50 100755
--- a/examples/changelog/changelog_to_file
+++ b/examples/changelog/changelog_to_file
@@ -16,6 +16,8 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+from __future__ import print_function
+
from debian.changelog import Changelog, Version
import sys
@@ -36,7 +38,7 @@ changelog.add_change('');
try:
filename = sys.argv[1]
except IndexError:
- print "Usage: "+sys.argv[0]+" filename"
+ print("Usage: "+sys.argv[0]+" filename")
sys.exit(1)
f = open(filename, 'w')
diff --git a/examples/changelog/simple_changelog b/examples/changelog/simple_changelog
index 86de0f7..0b70051 100755
--- a/examples/changelog/simple_changelog
+++ b/examples/changelog/simple_changelog
@@ -16,6 +16,8 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+from __future__ import print_function
+
from debian.changelog import Changelog, Version
changelog = Changelog()
@@ -32,5 +34,5 @@ changelog.add_change('');
changelog.add_change(' * Welcome to changelog.py');
changelog.add_change('');
-print changelog
+print(changelog)
diff --git a/examples/deb822/depgraph b/examples/deb822/depgraph
index d2b6782..388020a 100755
--- a/examples/deb822/depgraph
+++ b/examples/deb822/depgraph
@@ -16,6 +16,8 @@ were not versioned. The graph is retourned in output as a (non normalized)
graphviz graph suitable to be processed by dot (for an unstable/main Packages
file, generating the final graph will take a while ...)."""
+from __future__ import print_function
+
import sys
from debian import deb822
@@ -23,7 +25,7 @@ __fresh_id = 0
def main():
if len(sys.argv) != 2:
- print "Usage: depgraph PACKAGES_FILE"
+ print("Usage: depgraph PACKAGES_FILE")
sys.exit(2)
def get_id():
@@ -32,11 +34,11 @@ def main():
return ("NODE_%d" % __fresh_id)
def emit_arc(node1, node2):
- print ' "%s" -> "%s" ;' % (node1, node2)
+ print(' "%s" -> "%s" ;' % (node1, node2))
def emit_node(node, dsc):
- print ' "%s" [label="%s"] ;' % (node, dsc)
+ print(' "%s" [label="%s"] ;' % (node, dsc))
- print "digraph depgraph {"
+ print("digraph depgraph {")
for pkg in deb822.Packages.iter_paragraphs(file(sys.argv[1])):
name = pkg['package']
rels = pkg.relations
@@ -52,7 +54,7 @@ def main():
# even though it is forbidden by policy, there are some
# dependencies with upper case letter in the archive,
# apparently apt-get turn them to lowercase ...
- print "}"
+ print("}")
if __name__ == '__main__':
main()
diff --git a/examples/deb822/grep-maintainer b/examples/deb822/grep-maintainer
index 53a956c..358bf7e 100755
--- a/examples/deb822/grep-maintainer
+++ b/examples/deb822/grep-maintainer
@@ -10,6 +10,8 @@
"""Dumb maintainer-based grep for the dpkg status file."""
+from __future__ import print_function
+
import re
import sys
from debian import deb822
@@ -17,13 +19,13 @@ from debian import deb822
try:
maint_RE = re.compile(sys.argv[1])
except IndexError:
- print >>sys.stderr, "Usage: grep-maintainer REGEXP"
+ print("Usage: grep-maintainer REGEXP", file=sys.stderr)
sys.exit(1)
except re.error as e:
- print >>sys.stderr, "Error in the regexp: %s" % (e,)
+ print("Error in the regexp: %s" % (e,), file=sys.stderr)
sys.exit(1)
for pkg in deb822.Packages.iter_paragraphs(file('/var/lib/dpkg/status')):
if pkg.has_key('Maintainer') and maint_RE.search(pkg['maintainer']):
- print pkg['package']
+ print(pkg['package'])
diff --git a/examples/deb822/grep_native_packages.py b/examples/deb822/grep_native_packages.py
index ab8c5cc..dea04f4 100755
--- a/examples/deb822/grep_native_packages.py
+++ b/examples/deb822/grep_native_packages.py
@@ -8,6 +8,8 @@
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
+from __future__ import print_function
+
import sys
from debian import deb822
@@ -17,6 +19,6 @@ for fname in sys.argv[1:]:
for stanza in deb822.Sources.iter_paragraphs(f):
pieces = stanza['version'].split('-')
if len(pieces) < 2:
- print stanza['package']
+ print(stanza['package'])
f.close()
diff --git a/examples/deb822/render-dctrl b/examples/deb822/render-dctrl
index 081bd4e..6ed4e55 100755
--- a/examples/deb822/render-dctrl
+++ b/examples/deb822/render-dctrl
@@ -10,6 +10,8 @@
# Requirements (Debian packages): python-debian python-markdown
+from __future__ import print_function
+
usage = """Usage: render-dctrl [OPTION ...] [FILE ...]
Render a 822-like listing of Debian packages (AKA "Packages" file) to
@@ -93,7 +95,7 @@ def get_indent(s):
return 0
def render_longdesc(lines):
- print '<div class="longdesc">'
+ print('<div class="longdesc">')
lines = map(lambda s: s[1:], lines) # strip 822 heading space
curpara, paragraphs = [], []
inlist, listindent = False, 0
@@ -127,40 +129,40 @@ def render_longdesc(lines):
store_para()
for p in paragraphs: # render paragraphs
- print markdown(p)
- print '</div>'
+ print(markdown(p))
+ print('</div>')
def render_field(field, val):
field = field.lower()
- print '<dt>%s</dt>' % field
- print '<dd class="%s">' % field
+ print('<dt>%s</dt>' % field)
+ print('<dd class="%s">' % field)
if field == 'description':
lines = val.split('\n')
- print '<span class="shortdesc">%s</span>' % lines[0]
+ print('<span class="shortdesc">%s</span>' % lines[0])
render_longdesc(lines[1:])
elif field == 'package':
- print '<a href="#%s" class="uid">id</a>' % val
- print '<span id="%s" class="package">%s</span>' % (val, val)
+ print('<a href="#%s" class="uid">id</a>' % val)
+ print('<span id="%s" class="package">%s</span>' % (val, val))
elif field in []: # fields not to be typeset as "raw"
- print '<span class="%s">%s</span>' % (field, val)
+ print('<span class="%s">%s</span>' % (field, val))
else:
- print '<span class="raw">%s</span>' % val
- print '</dd>'
+ print('<span class="raw">%s</span>' % val)
+ print('</dd>')
def render_file(f):
global options, html_header, html_trailer
if options.print_header:
- print html_header
+ print(html_header)
for pkg in deb822.Packages.iter_paragraphs(f):
- print '<div class="package">'
- print '<dl class="fields">'
+ print('<div class="package">')
+ print('<dl class="fields">')
for (field, val) in pkg.iteritems():
render_field(field, val)
- print '</dl>'
- print '</div>\n'
+ print('</dl>')
+ print('</div>\n')
if options.print_header:
- print html_trailer
+ print(html_trailer)
def main():
global options, usage
diff --git a/examples/debfile/ar b/examples/debfile/ar
index ee99140..71436a6 100755
--- a/examples/debfile/ar
+++ b/examples/debfile/ar
@@ -16,6 +16,8 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+from __future__ import print_function
+
import os
import sys
@@ -23,18 +25,18 @@ from debian import arfile
if __name__ == '__main__':
if len(sys.argv) < 3:
- print "usage: arfile.py [tp] <arfile>"
+ print("usage: arfile.py [tp] <arfile>")
sys.exit(1)
if not os.path.exists(sys.argv[2]):
- print "please provide a file to operate on"
+ print("please provide a file to operate on")
sys.exit(1)
a = arfile.ArFile(sys.argv[2])
if sys.argv[1] == 't':
- print "\n".join(a.getnames())
+ print("\n".join(a.getnames()))
elif sys.argv[1] == 'p':
for m in a.getmembers():
- #print "".join(m.readlines())
+ #print("".join(m.readlines()))
sys.stdout.write("".join(m.readlines()))
diff --git a/examples/debfile/changelog_head b/examples/debfile/changelog_head
index 4410f1c..83a8bec 100755
--- a/examples/debfile/changelog_head
+++ b/examples/debfile/changelog_head
@@ -11,6 +11,8 @@
"""Like "head" for changelog entries, return last n-th entries of the changelog
shipped in a .deb file."""
+from __future__ import print_function
+
import string
import sys
@@ -18,8 +20,8 @@ from debian import debfile
if __name__ == '__main__':
if len(sys.argv) > 3 or len(sys.argv) < 2:
- print "Usage: changelog_head DEB [ENTRIES]"
- print " ENTRIES defaults to 10"
+ print("Usage: changelog_head DEB [ENTRIES]")
+ print(" ENTRIES defaults to 10")
sys.exit(1)
entries = 10
@@ -31,5 +33,5 @@ if __name__ == '__main__':
deb = debfile.DebFile(sys.argv[1])
chg = deb.changelog()
entries = chg._blocks[:entries]
- print string.join(map(str, entries), '')
+ print(string.join(map(str, entries)))
diff --git a/examples/debfile/dpkg-info b/examples/debfile/dpkg-info
index b060bf4..a565bf4 100755
--- a/examples/debfile/dpkg-info
+++ b/examples/debfile/dpkg-info
@@ -12,6 +12,8 @@
""" (An approximation of) a 'dpkg --info' implementation relying on DebFile
class. """
+from __future__ import print_function
+
import os
import stat
import string
@@ -21,15 +23,15 @@ from debian import debfile
if __name__ == '__main__':
if len(sys.argv) != 2:
- print "Usage: dpkg-info DEB"
+ print("Usage: dpkg-info DEB")
sys.exit(1)
fname = sys.argv[1]
deb = debfile.DebFile(fname)
if deb.version == '2.0':
- print ' new debian package, version %s.' % deb.version
- print ' size %d bytes: control archive= %d bytes.' % (
- os.stat(fname)[stat.ST_SIZE], deb['control.tar.gz'].size)
+ print(' new debian package, version %s.' % deb.version)
+ print(' size %d bytes: control archive= %d bytes.' % (
+ os.stat(fname)[stat.ST_SIZE], deb['control.tar.gz'].size))
for fname in deb.control: # print info about control part contents
content = deb.control[fname]
if not content:
@@ -41,14 +43,14 @@ if __name__ == '__main__':
ftype = lines[0].split()[0]
except IndexError:
pass
- print ' %d bytes, %d lines, %s, %s' % (len(content), len(lines),
- fname, ftype)
+ print(' %d bytes, %d lines, %s, %s' % (len(content), len(lines),
+ fname, ftype))
for n, v in deb.debcontrol().iteritems(): # print DEBIAN/control fields
if n.lower() == 'description': # increase indentation of long dsc
lines = v.split('\n')
short_dsc = lines[0]
long_dsc = string.join(map(lambda l: ' ' + l, lines[1:]), '\n')
- print ' %s: %s\n%s' % (n, short_dsc, long_dsc)
+ print(' %s: %s\n%s' % (n, short_dsc, long_dsc))
else:
- print ' %s: %s' % (n, v)
+ print(' %s: %s' % (n, v))
diff --git a/examples/debfile/extract_cron b/examples/debfile/extract_cron
index 2de005b..2c46019 100755
--- a/examples/debfile/extract_cron
+++ b/examples/debfile/extract_cron
@@ -10,6 +10,8 @@
"""Extracts all cron-related files from a (list of) .deb package(s)."""
+from __future__ import print_function
+
import os
import re
import sys
@@ -21,14 +23,14 @@ def is_cron(fname):
if __name__ == '__main__':
if not sys.argv[1:]:
- print "Usage: extract_cron DEB ..."
+ print("Usage: extract_cron DEB ...")
sys.exit(1)
for fname in sys.argv[1:]:
deb = debfile.DebFile(fname)
cron_files = filter(is_cron, list(deb.data))
for cron_file in cron_files:
- print 'Extracting cron-related file %s ...' % cron_file
+ print('Extracting cron-related file %s ...' % cron_file)
path = os.path.join('.', cron_file)
dir = os.path.dirname(path)
if not os.path.exists(dir):
diff --git a/examples/debtags/pkgwalk b/examples/debtags/pkgwalk
index d6ec2bb..6babd45 100755
--- a/examples/debtags/pkgwalk
+++ b/examples/debtags/pkgwalk
@@ -9,6 +9,8 @@
# Navigate among related Debian packages
+from __future__ import print_function
+
import sys
# Requires python-extractor, python-magic and python-debtags
@@ -99,7 +101,7 @@ if __name__ == '__main__':
for num, pkg in enumerate(display):
aptpkg = apt_cache[pkg]
desc = aptpkg.raw_description.split("\n")[0]
- print "%2d) %s - %s" % (num + 1, pkg, desc)
+ print("%2d) %s - %s" % (num + 1, pkg, desc))
# Ask the user to choose a new package
while True:
@@ -115,7 +117,7 @@ if __name__ == '__main__':
trail = [display[num]] + trail[:maxlen]
break
else:
- print "The number is too high"
+ print("The number is too high")
# vim:set ts=4 sw=4:
diff --git a/examples/debtags/reverse b/examples/debtags/reverse
index b741f81..60c46fe 100755
--- a/examples/debtags/reverse
+++ b/examples/debtags/reverse
@@ -18,6 +18,8 @@
# along 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 print_function
+
import sys
from debian import debtags
@@ -33,4 +35,4 @@ db = debtags.read_tag_database_reversed(input)
for pkg, tags in db.items():
# Using % here seems awkward to me, but if I use calls to
# sys.stdout.write it becomes a bit slower
- print "%s:" % (pkg), ", ".join(tags)
+ print("%s:" % (pkg), ", ".join(tags))
diff --git a/examples/debtags/smartsearch b/examples/debtags/smartsearch
index ec298cf..5873aa3 100755
--- a/examples/debtags/smartsearch
+++ b/examples/debtags/smartsearch
@@ -18,6 +18,8 @@
# along 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 print_function
+
import sys
import re
import subprocess
@@ -49,7 +51,7 @@ class SmartSearcher:
pkgs = []
for pkg in input.stdout:
pkg, none = pkg.rstrip("\n").split(' - ', 1)
- #print pkg
+ #print(pkg)
pkgs.append(pkg)
subcoll = self.fullcoll.choose_packages(pkgs)
@@ -74,15 +76,15 @@ class SmartSearcher:
def show_set(self, tags, type):
for tag in tags:
self.tags_in_menu.append(tag)
- print "%d) %s (%s)" % (len(self.tags_in_menu), tag, type)
+ print("%d) %s (%s)" % (len(self.tags_in_menu), tag, type))
def show_choice_sequence(self, seq, max = 7):
for tag in seq:
if tag in self.wanted or tag in self.unwanted or tag in self.ignored:
continue
self.tags_in_menu.append(tag)
- print "%d) %s (%d/%d)" % \
- (len(self.tags_in_menu), tag, self.subcoll.card(tag), self.subcoll.package_count())
+ print("%d) %s (%d/%d)" % \
+ (len(self.tags_in_menu), tag, self.subcoll.card(tag), self.subcoll.package_count()))
max = max - 1
if max == 0: break
@@ -103,14 +105,14 @@ class SmartSearcher:
for pkg in self.subcoll.iter_packages():
aptpkg = self.apt_cache[pkg]
desc = aptpkg.raw_description.split("\n")[0]
- print pkg, "-", desc
+ print(pkg, "-", desc)
def interact(self):
done = False
while not done:
- print "Tag selection:"
+ print("Tag selection:")
self.show_tags()
- print self.subcoll.package_count(), " packages selected so far."
+ print(self.subcoll.package_count(), " packages selected so far.")
changed = False
@@ -123,19 +125,19 @@ class SmartSearcher:
# If we're setting a new keyword search, process now and skip
# processing as a list
if ans == "?":
- print "+ number select the tag with the given number as a tag you want"
- print "- number select the tag with the given number as a tag you do not want"
- print "= number select the tag with the given number as a tag you don't care about"
- print "K word recompute the set of interesting tags from a full-text search using the given word"
- print "V view the packages selected so far"
- print "D print the packages selected so far and exit"
- print "Q quit debtags smart search"
- print "? print this help information"
+ print("+ number select the tag with the given number as a tag you want")
+ print("- number select the tag with the given number as a tag you do not want")
+ print("= number select the tag with the given number as a tag you don't care about")
+ print("K word recompute the set of interesting tags from a full-text search using the given word")
+ print("V view the packages selected so far")
+ print("D print the packages selected so far and exit")
+ print("Q quit debtags smart search")
+ print("? print this help information")
elif ans[0] == 'k' or ans[0] == 'K':
# Strip initial command and empty spaces
ans = ans[1:].strip();
if len(ans) == 0:
- print "The 'k' command needs a keyword to use for finding new interesting tags."
+ print("The 'k' command needs a keyword to use for finding new interesting tags.")
else:
self.compute_interesting(ans)
ans = ''
@@ -146,10 +148,10 @@ class SmartSearcher:
try:
idx = int(cmd[1:])
except ValueError:
- print cmd, "should have a number after +, - or ="
+ print(cmd, "should have a number after +, - or =")
continue
if idx > len(self.tags_in_menu):
- print "Tag", idx, "was not on the menu."
+ print("Tag", idx, "was not on the menu.")
else:
tag = self.tags_in_menu[idx - 1]
# cout << "Understood " << ans << " as " << ans[0] << tag.fullname() << endl;
@@ -175,13 +177,13 @@ class SmartSearcher:
elif cmd == "Q" or cmd == "q":
done = True;
else:
- print "Ignoring command \"%s\"" % (cmd)
+ print("Ignoring command \"%s\"" % (cmd))
if changed:
self.refilter()
if len(sys.argv) < 3:
- print sys.stderr, "Usage: %s tagdb keywords..." % (sys.argv[0])
+ print("Usage: %s tagdb keywords..." % (sys.argv[0]), file=sys.stderr)
sys.exit(1)
diff --git a/examples/debtags/tagminer b/examples/debtags/tagminer
index ced2876..d5c2e97 100755
--- a/examples/debtags/tagminer
+++ b/examples/debtags/tagminer
@@ -9,6 +9,8 @@
# Given a file, search Debian packages that can somehow handle it
+from __future__ import print_function
+
import sys
# Requires python-extractor, python-magic and python-debtags
@@ -125,7 +127,7 @@ if __name__ == '__main__':
fullcoll.read(open(options.tagdb, "r"), lambda x: not tag_filter.match(x))
type = mimetype(args[0])
- #print >>sys.stderr, "Mime type:", type
+ #print("Mime type:", type, file=sys.stderr)
found = set()
for match, tags in mime_map:
match = re.compile(match)
@@ -133,26 +135,26 @@ if __name__ == '__main__':
for t in tags:
found.add(t)
if len(found) == 0:
- print >>sys.stderr, "Unhandled mime type:", type
+ print("Unhandled mime type:", type, file=sys.stderr)
else:
if options.action != None:
apt_cache = apt.Cache()
query = found.copy()
query.add("role::program")
query.add("use::"+options.action)
- print "Debtags query:", " && ".join(query)
+ print("Debtags query:", " && ".join(query))
subcoll = fullcoll.filter_packages_tags(lambda pt: query.issubset(pt[1]))
for i in subcoll.iter_packages():
aptpkg = apt_cache[i]
desc = aptpkg.raw_description.split("\n")[0]
- print i, "-", desc
+ print(i, "-", desc)
else:
- print "Debtags query:", " && ".join(found)
+ print("Debtags query:", " && ".join(found))
query = found.copy()
query.add("role::program")
subcoll = fullcoll.filter_packages_tags(lambda pt: query.issubset(pt[1]))
uses = map(lambda x:x[5:], filter(lambda x:x.startswith("use::"), subcoll.iter_tags()))
- print "Available actions:", ", ".join(uses)
+ print("Available actions:", ", ".join(uses))
# vim:set ts=4 sw=4:
diff --git a/examples/debtags/tagsbyrelevance b/examples/debtags/tagsbyrelevance
index 2633c12..d5ef8c2 100644
--- a/examples/debtags/tagsbyrelevance
+++ b/examples/debtags/tagsbyrelevance
@@ -18,12 +18,14 @@
# along 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 print_function
+
import sys
import re
from debian import debtags
if len(sys.argv) < 2:
- print sys.stderr, "Usage: %s tagdb [packagelist]" % (sys.argv[0])
+ print("Usage: %s tagdb [packagelist]" % (sys.argv[0]), file=sys.stderr)
sys.exit(1)
full = debtags.DB()
@@ -48,5 +50,5 @@ tags = sorted(sub.iter_tags(), lambda a, b: cmp(rel_index(a), rel_index(b)))
## And finally print them
for tag in tags:
- print tag
- #print tag, sub.card(tag), full.card(tag), float(sub.card(tag)) / float(full.card(tag))
+ print(tag)
+ #print(tag, sub.card(tag), full.card(tag), float(sub.card(tag)) / float(full.card(tag)))
diff --git a/examples/debtags/wxssearch b/examples/debtags/wxssearch
index a0aeb37..79ce0a1 100755
--- a/examples/debtags/wxssearch
+++ b/examples/debtags/wxssearch
@@ -18,6 +18,8 @@
# along 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 print_function
+
import wx
import wx.html
import wx.lib.dialogs
@@ -73,9 +75,9 @@ class Model(wx.EvtHandler):
# Compute the most interesting tags by discriminance
self.discriminant = sorted(self.subcoll.iter_tags(), \
lambda b, a: cmp(self.subcoll.discriminance(a), self.subcoll.discriminance(b)))
- #print "-----------------------------"
+ #print("-----------------------------")
#for d in self.discriminant:
- # print d, self.subcoll.discriminance(d)
+ # print(d, self.subcoll.discriminance(d))
# Notify the change
e = Model.ModelEvent(Model.wxEVT_CHANGED)
@@ -168,7 +170,7 @@ class TagList(wx.html.HtmlWindow):
self.ProcessEvent(e)
def model_changed(self, event):
- #print "TLMC"
+ #print("TLMC")
self.SetPage("<html><body>")
first = True
@@ -381,12 +383,12 @@ class SearchWindow(wx.Frame):
if action == 'add':
self.model.add_wanted(tag)
elif action == 'addnot':
- print "wanted_event -> addnot"
+ print("wanted_event -> addnot")
self.model.add_unwanted(tag)
elif action == 'del':
self.model.remove_tag_from_filter(tag)
else:
- print "Unknown action", action
+ print("Unknown action", action)
def go_button_pressed(self, event):
self.model.set_query(self.query.GetValue())
--
1.7.2.5
More information about the pkg-python-debian-commits
mailing list