Update print and input syntax for python 3
authorMagnus Hagander <magnus@hagander.net>
Sat, 19 Jan 2019 19:09:24 +0000 (20:09 +0100)
committerMagnus Hagander <magnus@hagander.net>
Sat, 26 Jan 2019 15:19:26 +0000 (16:19 +0100)
16 files changed:
pgweb/core/management/commands/cleanup_old_records.py
pgweb/core/management/commands/sessioninfo.py
pgweb/lists/management/commands/sync_lists.py
pgweb/news/management/commands/twitter_register.py
tools/communityauth/generate_cryptkey.py
tools/communityauth/test_auth.py
tools/docs/docload.py
tools/ftp/spider_ftp.py
tools/ftp/spider_yum.py
tools/localhtmlvalidate/localhtmlvalidate.py
tools/search/crawler/lib/archives.py
tools/search/crawler/lib/log.py
tools/search/crawler/lib/threadwrapper.py
tools/search/crawler/listcrawler.py
tools/varnishqueue/nagios_check.py
tools/varnishqueue/varnish_queue.py

index 27d3bc13b0ccbf944f50b9017398ffb621dd7d9a..a2fb38c49298c06dacdd2a7fdd0ed593423e15ed 100644 (file)
@@ -28,7 +28,7 @@ class Command(BaseCommand):
         curs = connection.cursor()
         curs.execute("SELECT pg_try_advisory_lock(2896719)")
         if not curs.fetchall()[0][0]:
-                print "Failed to get advisory lock, existing cleanup_old_records process stuck?"
+                print("Failed to get advisory lock, existing cleanup_old_records process stuck?")
                 sys.exit(1)
 
         # Clean up old email change tokens
index 0b8e2fdb8d11edb7177092b0ec319eaceae4911e..622b0a4a5f664f024dba2a9e7e4f4257dedc3210 100644 (file)
@@ -18,25 +18,25 @@ class Command(BaseCommand):
             session = Session.objects.get(session_key=options['sessionid']).get_decoded()
             uid = session.get('_auth_user_id')
 
-            print u"Session {0}".format(options['sessionid'])
+            print("Session {0}".format(options['sessionid']))
 
             try:
                 user = User.objects.get(pk=uid)
-                print " -- Logged in user --"
-                print u"Userid:   {0}".format(uid)
-                print u"Username: {0}".format(user.username)
-                print u"Name:     {0}".format(user.get_full_name())
-                print u"Email:    {0}".format(user.email)
+                print(" -- Logged in user --")
+                print("Userid:   {0}".format(uid))
+                print("Username: {0}".format(user.username))
+                print("Name:     {0}".format(user.get_full_name()))
+                print("Email:    {0}".format(user.email))
             except User.DoesNotExist:
-                print "** Associated user not found. Maybe not logged in?"
+                print("** Associated user not found. Maybe not logged in?")
 
             # Remove known keys
             for k in ('_auth_user_id', '_auth_user_hash', '_auth_user_backend'):
                 session.pop(k, None)
             if session:
-                print " -- Other session values --"
-                for k, v in session.items():
-                    print u"{0:20} {1}".format(k, v)
+                print(" -- Other session values --")
+                for k, v in list(session.items()):
+                    print("{0:20} {1}".format(k, v))
 
         except Session.DoesNotExist:
             raise CommandError('Session not found')
index 1c6e94f1bec2a26bc420e95267b0c6359b11f737..b9892a8331670a9c785c8220f4e1ff45d520e928 100644 (file)
@@ -28,7 +28,7 @@ class Command(BaseCommand):
             # Add any groups necessary
             curs.execute("INSERT INTO lists_mailinglistgroup (groupname, sortkey) SELECT n,50 FROM UNNEST(%s) n(n) WHERE NOT EXISTS (SELECT 1 FROM lists_mailinglistgroup WHERE groupname=n) RETURNING groupname", (allgroups,))
             for n, in curs.fetchall():
-                print "Added group %s" % n
+                print("Added group %s" % n)
 
             # Add and update lists
             for l in j:
@@ -36,7 +36,7 @@ class Command(BaseCommand):
                 if curs.rowcount == 0:
                     curs.execute("INSERT INTO lists_mailinglist (listname, group_id, active, description, shortdesc) VALUES (%s, (SELECT id FROM lists_mailinglistgroup WHERE groupname=%s), %s, %s, %s)", (
                         l['name'], l['group'], l['active'], l['description'], l['shortdesc']))
-                    print "Added list %s" % l['name']
+                    print("Added list %s" % l['name'])
                 else:
                     curs.execute("UPDATE lists_mailinglist SET group_id=(SELECT id FROM lists_mailinglistgroup WHERE groupname=%s), active=%s, description=%s, shortdesc=%s WHERE listname=%s AND NOT (group_id=(SELECT id FROM lists_mailinglistgroup WHERE groupname=%s) AND active=%s AND description=%s AND shortdesc=%s) RETURNING listname", (
                         l['group'], l['active'], l['description'], l['shortdesc'],
@@ -44,17 +44,17 @@ class Command(BaseCommand):
                         l['group'], l['active'], l['description'], l['shortdesc'],
                     ))
                     for n, in curs.fetchall():
-                        print "Updated list %s" % n
+                        print("Updated list %s" % n)
 
             # Delete any lists that shouldn't exist anymore (this is safe because we don't keep any data about them,
             # so they are trivial to add back)
             curs.execute("DELETE FROM lists_mailinglist WHERE NOT listname=ANY(%s) RETURNING listname", ([l['name'] for l in j],))
             for n, in curs.fetchall():
-                print "Deleted list %s" % n
+                print("Deleted list %s" % n)
             # Delete listgroups
             curs.execute("DELETE FROM lists_mailinglistgroup WHERE NOT groupname=ANY(%s) RETURNING groupname", (allgroups,))
             for n, in curs.fetchall():
-                print "Deleted group %s" % n
+                print("Deleted group %s" % n)
 
             if options['dryrun']:
                 raise CommandError("Dry run, rolling back")
index 0b9113925ac997d7311cc97ba14b08f6ad883b74..b6c34c9597fbf4d1689ad7107131546e02ec05cd 100644 (file)
@@ -28,9 +28,9 @@ class Command(BaseCommand):
         fetch_response = oauth.fetch_request_token('https://api.twitter.com/oauth/request_token')
 
         authorization_url = oauth.authorization_url('https://api.twitter.com/oauth/authorize')
-        print 'Please go here and authorize: %s' % authorization_url
+        print('Please go here and authorize: %s' % authorization_url)
 
-        pin = raw_input('Paste the PIN here: ')
+        pin = input('Paste the PIN here: ')
 
         oauth = requests_oauthlib.OAuth1Session(settings.TWITTER_CLIENT,
                                                 settings.TWITTER_CLIENTSECRET,
index aaf17e0425be9de7e48a5a03ca22e085c84bde4f..9585f6c8e00c73cacabfa8c97f44a453334eedd6 100755 (executable)
@@ -9,10 +9,10 @@ from Crypto import Random
 import base64
 
 if __name__ == "__main__":
-    print "The next row contains a 32-byte (256-bit) symmetric crypto key."
-    print "This key should be used to integrate a community auth site."
-    print "Note that each site should have it's own key!!"
-    print ""
+    print("The next row contains a 32-byte (256-bit) symmetric crypto key.")
+    print("This key should be used to integrate a community auth site.")
+    print("Note that each site should have it's own key!!")
+    print("")
 
     r = Random.new()
     key = r.read(32)
index a1d9747ecc2f4e7a87d54728328390cb80b510eb..26b36ecfab8dbe4cebf3ce8ad665f74c39db5cc7 100755 (executable)
@@ -30,9 +30,9 @@ if __name__ == "__main__":
         sys.exit(1)
 
     if not options.key:
-        options.key = raw_input("Enter key (BASE64 encoded): ")
+        options.key = input("Enter key (BASE64 encoded): ")
     if not options.user:
-        options.user = raw_input("Enter username: ")
+        options.user = input("Enter username: ")
     if not options.first:
         options.first = "FirstName"
     if not options.last:
index 1e4d08f3a678b75c0f517ef11644c93b91f29c91..53204fb6f660bf3d0b08d6a85686b766ac8627de 100755 (executable)
@@ -56,7 +56,7 @@ def load_doc_file(filename, f):
     else:
         title = ""
     if not quiet:
-        print "--- file: %s (%s) ---" % (filename, title)
+        print("--- file: %s (%s) ---" % (filename, title))
 
     s = tidy.parseString(contents.encode('utf-8'), **tidyopts)
     curs.execute("INSERT INTO docs (file, version, title, content) VALUES (%(f)s, %(v)s, %(t)s, %(c)s)", {
@@ -87,7 +87,7 @@ config = ConfigParser()
 config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'docload.ini'))
 
 if not os.path.isfile(tarfilename):
-    print "File %s not found" % tarfilename
+    print("File %s not found" % tarfilename)
     sys.exit(1)
 
 tf = tarfile.open(tarfilename)
@@ -99,7 +99,7 @@ curs = connection.cursor()
 curs.execute("SELECT current FROM core_version WHERE tree=%(v)s", {'v': ver})
 r = curs.fetchall()
 if len(r) != 1:
-    print "Version %s not found in the system, cannot load!" % ver
+    print("Version %s not found in the system, cannot load!" % ver)
     sys.exit(1)
 
 iscurrent = r[0][0]
@@ -143,4 +143,4 @@ connection.commit()
 connection.close()
 
 if not quiet:
-    print "Done (%i pages)." % pagecount
+    print("Done (%i pages)." % pagecount)
index 557baa75abcdb67544b8181028bc7cbf72f8471d..f4100df899fb01084cdbd48b7dfdf95da19e18fb 100755 (executable)
@@ -67,10 +67,10 @@ def parse_directory(dirname, rootlen):
 
 
 def Usage():
-    print "Usage: spider_ftp.py <ftp_root> <pickle_file>"
-    print ""
-    print "If <pickle_file> starts with http[s]://, the file will be uploaded"
-    print "to that URL instead of written to the filesystem."
+    print("Usage: spider_ftp.py <ftp_root> <pickle_file>")
+    print("")
+    print("If <pickle_file> starts with http[s]://, the file will be uploaded")
+    print("to that URL instead of written to the filesystem.")
     sys.exit(1)
 
 
@@ -88,7 +88,7 @@ if sys.argv[2].startswith("http://") or sys.argv[2].startswith("https://"):
     u = o.open(r)
     x = u.read()
     if x != "NOT CHANGED" and x != "OK":
-        print "Failed to upload: %s" % x
+        print("Failed to upload: %s" % x)
         sys.exit(1)
 else:
     f = open(sys.argv[2] + ".tmp", "wb")
index 36e248a4d215a1184e1bad25e2f79068b414a507..05b836911e754f74fa914c932e54b45ed73043fa 100755 (executable)
@@ -96,15 +96,15 @@ if __name__ == "__main__":
     j = json.dumps({'platforms': platforms, 'reporpms': reporpms})
 
     if args.target.startswith('http://') or args.target.startswith('https://'):
-        o = urllib2.build_opener(urllib2.HTTPHandler)
-        r = urllib2.Request(sys.argv[2], data=j)
+        o = urllib.request.build_opener(urllib.request.HTTPHandler)
+        r = urllib.request.Request(sys.argv[2], data=j)
         r.add_header('Content-type', 'application/json')
         r.add_header('Host', 'www.postgresql.org')
         r.get_method = lambda: 'PUT'
         u = o.open(r)
         x = u.read()
         if x != "NOT CHANGED" and x != "OK":
-            print "Failed to upload: %s" % x
+            print("Failed to upload: %s" % x)
             sys.exit(1)
     else:
         with NamedTemporaryFile(dir=os.path.dirname(os.path.abspath(args.target))) as f:
index 56fe892094c8e264d6d64010c2a6b9c852b26419..084775719755618f7f788af749c6c34359710026 100755 (executable)
@@ -43,7 +43,7 @@ def encode_multipart_formdata(fields, files):
 
 if __name__ == "__main__":
     if len(sys.argv) != 2:
-        print "Usage: localhtmlvalidate.py <local url>"
+        print("Usage: localhtmlvalidate.py <local url>")
         sys.exit(1)
 
     contents = urllib.urlopen(sys.argv[1]).read()
@@ -76,23 +76,23 @@ if __name__ == "__main__":
     errcode, errmsg, headers = h.getreply()
     rbody = h.getfile().read()
     if headers['x-w3c-validator-status'] == 'Valid':
-        print "Page validates!"
+        print("Page validates!")
         sys.exit(0)
     elif headers['x-w3c-validator-status'] == 'Invalid':
-        print "Invalid!"
-        print "Errors: %s" % headers['x-w3c-validator-errors']
-        print "Warnings: %s" % headers['x-w3c-validator-warnings']
+        print("Invalid!")
+        print("Errors: %s" % headers['x-w3c-validator-errors'])
+        print("Warnings: %s" % headers['x-w3c-validator-warnings'])
         hp = HTMLParser.HTMLParser()
         for m in re.findall('<li class="msg_err">.*?</li>', rbody, re.DOTALL):
             r = re.search('<em>Line (\d+).*<span class="msg">(.*?)</span>', m, re.DOTALL)
-            print "Line %s (should be around %s): %s" % (r.group(1), int(r.group(1)) - firstline, hp.unescape(r.group(2)))
+            print("Line %s (should be around %s): %s" % (r.group(1), int(r.group(1)) - firstline, hp.unescape(r.group(2))))
 
             r2 = re.search('<code class="input">(.*?)<strong title=".*?">(.*?)</strong>(.*?)</code>', unicode(m, 'utf8'), re.DOTALL)
             if r2:
-                s = u"%s%s%s" % r2.groups()
-                print "Source: %s" % hp.unescape(s).encode('utf-8')
-            print ""
+                s = "%s%s%s" % r2.groups()
+                print("Source: %s" % hp.unescape(s).encode('utf-8'))
+            print("")
     else:
-        print "Unknown status: %s" % headers['x-w3c-validator-status']
-        print headers
+        print("Unknown status: %s" % headers['x-w3c-validator-status'])
+        print(headers)
         sys.exit(1)
index 1e42a8bac2c427a45ff6d2439cae85afc89de8f0..2235dbb38727c50c6508428220462ca1b97cf727 100644 (file)
@@ -35,12 +35,12 @@ class MultiListCrawler(object):
                 # Do one specific month
                 pieces = month.split("-")
                 if len(pieces) != 2:
-                    print "Month format is <y>-<m>, cannot parse '%s'" % month
+                    print("Month format is <y>-<m>, cannot parse '%s'" % month)
                     sys.exit(1)
                 try:
                     pieces = [int(x) for x in pieces]
                 except:
-                    print "Month format is <y>-<m>, cannot convert '%s' to integers" % month
+                    print("Month format is <y>-<m>, cannot convert '%s' to integers" % month)
                     sys.exit(1)
                 self.queue.put((listid, listname, pieces[0], pieces[1], -1))
             else:
index 08e8de5c03d0e03beeafb7f4ab9994befd7c48bd..3a87f099244f970869169bb84d25d995f919d158 100644 (file)
@@ -4,4 +4,4 @@ import datetime
 
 
 def log(msg):
-    print "%s: %s" % (datetime.datetime.now(), msg)
+    print("%s: %s" % (datetime.datetime.now(), msg))
index e305dffc88a9ed1d065eee1f963e4deb5e3f9774..2a245f4a85c621e08d69ad80b62c59c21dd54cfc 100644 (file)
@@ -16,8 +16,8 @@ def threadwrapper(func, *args):
     try:
         p.join()
     except KeyboardInterrupt as e:
-        print "Keyboard interrupt, terminating child process!"
+        print("Keyboard interrupt, terminating child process!")
         p.terminate()
     except Exception as e:
-        print "Exception %s, terminating child process!" % e
+        print("Exception %s, terminating child process!" % e)
         p.terminate()
index 445086107e2ceae9de46a6652f085fc4a9ac5aca..5faac72e9c02da1ff9762ecf3f16ecf3fe313922 100755 (executable)
@@ -52,7 +52,7 @@ if __name__ == "__main__":
     (opt, args) = parser.parse_args()
 
     if opt.full and opt.month:
-        print "Can't use both full and specific month!"
+        print("Can't use both full and specific month!")
         sys.exit(1)
 
     # assign default values
index a7cbd011dfc8f9876023fe09e0e07ad3c6093e0b..b85452c2bcb3704d26be42c30c0c8dcd077265bc 100755 (executable)
@@ -11,7 +11,7 @@ CRITICAL_THRESHOLD = timedelta(minutes=15)
 
 if __name__ == "__main__":
     if len(sys.argv) != 2:
-        print "Usage: nagios_check.py <dsn>"
+        print("Usage: nagios_check.py <dsn>")
         sys.exit(1)
 
     conn = psycopg2.connect(sys.argv[1])
@@ -23,17 +23,17 @@ if __name__ == "__main__":
     conn.close()
 
     if len(rows) == 0:
-        print "OK, queue is empty"
+        print("OK, queue is empty")
         sys.exit(0)
 
     age = rows[0][0]
 
     if age < WARNING_THRESHOLD:
-        print "OK, queue age is %s" % age
+        print("OK, queue age is %s" % age)
         sys.exit(0)
     elif age < CRITICAL_THRESHOLD:
-        print "WARNING, queue age is %s" % age
+        print("WARNING, queue age is %s" % age)
         sys.exit(1)
     else:
-        print "CRITICAL, queue age is %s" % age
+        print("CRITICAL, queue age is %s" % age)
         sys.exit(2)
index 707493982b0f824b8d895595121e1e69dfdcd732..60eddce91c8dd004a7d92f43e568a2d1b14ebe37 100755 (executable)
@@ -111,7 +111,7 @@ def housekeeper(dsn):
 
 if __name__ == "__main__":
     if len(sys.argv) != 2:
-        print "Usage: varnish_queue.py <dsn>"
+        print("Usage: varnish_queue.py <dsn>")
         sys.exit(1)
 
     logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO)