From 6718706c65bd1c62c7396c3fc997084bdc1a2f54 Mon Sep 17 00:00:00 2001 From: "J. Borovec" Date: Thu, 12 Mar 2020 14:51:25 +0100 Subject: [PATCH 1/2] fix prints --- FAHControl | 9 +++++---- ez_setup.py | 30 +++++++++++++++++------------- fah/Client.py | 16 +++++++++------- fah/ClientConfig.py | 6 +++--- fah/Connection.py | 34 ++++++++++++++++------------------ fah/FAHControl.py | 40 ++++++++++++++++++++++------------------ fah/util/SingleApp.py | 2 +- fah/util/__init__.py | 8 ++++---- setup.py | 2 +- 9 files changed, 78 insertions(+), 69 deletions(-) diff --git a/FAHControl b/FAHControl index 4d1de464..80816808 100755 --- a/FAHControl +++ b/FAHControl @@ -54,8 +54,9 @@ if options.exit: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(single_app_addr) sock.send('EXIT') - if sock.recv(1024).strip() == 'OK': print 'Ok' - except Exception, e: pass + if sock.recv(1024).strip() == 'OK': print ('Ok') + except Exception as e: + pass sys.exit(0) @@ -77,5 +78,5 @@ else: try: app.run() -except Exception, e: - print e +except Exception as e: + print (e) diff --git a/ez_setup.py b/ez_setup.py index 1ff1d3e7..97f56a4f 100644 --- a/ez_setup.py +++ b/ez_setup.py @@ -13,6 +13,8 @@ This file can also be run as a script to install or upgrade setuptools. """ +from __future__ import print_function + import sys DEFAULT_VERSION = "0.6c11" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] @@ -63,8 +65,10 @@ } import sys, os -try: from hashlib import md5 -except ImportError: from md5 import md5 +try: + from hashlib import md5 +except ImportError: + from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: @@ -103,14 +107,14 @@ def do_download(): return do_download() try: pkg_resources.require("setuptools>="+version); return - except pkg_resources.VersionConflict, e: + except pkg_resources.VersionConflict as e: if was_imported: - print >>sys.stderr, ( + print ( "The required version of setuptools (>=%s) is not available, and\n" - "can't be installed while this script is running. Please install\n" + " can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" - ) % (version, e.args[0]) + % (version, e.args[0]), file=sys.stderr) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok @@ -216,10 +220,10 @@ def main(argv, version=DEFAULT_VERSION): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': - print >>sys.stderr, ( - "You have an obsolete version of setuptools installed. Please\n" - "remove it from your system entirely before rerunning this script." - ) + print ( + "You have an obsolete version of setuptools installed. Please\n" + " remove it from your system entirely before rerunning this script.", + file=sys.stderr) sys.exit(2) req = "setuptools>="+version @@ -238,8 +242,8 @@ def main(argv, version=DEFAULT_VERSION): from setuptools.command.easy_install import main main(argv) else: - print "Setuptools version",version,"or greater has been installed." - print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' + print ("Setuptools version %s or greater has been installed." % version) + print ('(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)') def update_md5(filenames): """Update our built-in md5 registry""" @@ -262,7 +266,7 @@ def update_md5(filenames): match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: - print >>sys.stderr, "Internal error!" + print ("Internal error!", file=sys.stderr) sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] diff --git a/fah/Client.py b/fah/Client.py index 09d1bceb..85b66e20 100644 --- a/fah/Client.py +++ b/fah/Client.py @@ -313,7 +313,8 @@ def process_error(self, app, data): self.error_messages.add(msg) app.error(msg) - else: print 'ERROR:', msg + else: + print ('ERROR: %s' % msg) app.set_status(msg) @@ -323,7 +324,8 @@ def process_configured(self, app, configured): def process_message(self, app, type, data): - if debug: print 'message:', type, data + if debug: + print ('message: %s %s' % (type, data)) if type == 'heartbeat': return if type == 'ppd': self.process_ppd(app, data) @@ -350,13 +352,13 @@ def update(self, app): for version, type, data in self.conn.messages: try: self.process_message(app, type, data) - except Exception, e: + except Exception as e: traceback.print_exc() self.conn.messages = [] - except Exception, e: - print e + except Exception as e: + print (e) # If client status has changed update UI newStatus = self.get_status() @@ -395,7 +397,7 @@ def close(self): self.conn.queue_command('quit') self.conn.write_some() - except Exception, e: - print e + except Exception as e: + print (e) self.conn.close() diff --git a/fah/ClientConfig.py b/fah/ClientConfig.py index 3fa4ac2d..9d84b5d5 100644 --- a/fah/ClientConfig.py +++ b/fah/ClientConfig.py @@ -359,7 +359,7 @@ def update_options(self, app): set_widget_str_value(widget, self.options[name]) except: # Don't let one bad widget kill everything - print 'WARNING: failed to set widget "%s"' % name + print ('WARNING: failed to set widget "%s"' % name) # Setup passkey and password entries app.passkey_validator.set_good() @@ -614,8 +614,8 @@ def check_option(model, path, iter, data): if value is None: options[name + '!'] = None else: options[name] = value - except Exception, e: # Don't let one bad widget kill everything - print 'WARNING: failed to save widget "%s": %s' % (name, e) + except Exception as e: # Don't let one bad widget kill everything + print ('WARNING: failed to save widget "%s": %s' % (name, e)) # Removed options for name in self.options: diff --git a/fah/Connection.py b/fah/Connection.py index c94b0aba..890347e0 100755 --- a/fah/Connection.py +++ b/fah/Connection.py @@ -104,7 +104,7 @@ def open(self): if err != 0 and not err in [ errno.EINPROGRESS, errno.EWOULDBLOCK, WSAEWOULDBLOCK]: self.fail_reason = 'connect' - raise Exception, 'Connection failed: ' + errno.errorcode[err] + raise Exception('Connection failed: ' + errno.errorcode[err]) if self.password: self.queue_command('auth "%s"' % self.password) map(self.queue_command, self.init_commands) @@ -124,14 +124,14 @@ def close(self): def connection_lost(self): - print 'Connection lost' + print ('Connection lost') self.close() self.fail_reason = 'closed' - raise Exception, 'Lost connection' + raise Exception('Lost connection') def connection_error(self, err, msg): - print 'Connection Error: %d: %s' % (err, msg) + print ('Connection Error: %d: %s' % (err, msg)) self.close() if err == errno.ECONNREFUSED: self.fail_reason = 'refused' elif err in [errno.ETIMEDOUT, errno.ENETDOWN, errno.ENETUNREACH]: @@ -153,7 +153,7 @@ def read_some(self): self.connection_lost() return 0 - except socket.error, (err, msg): + except socket.error as (err, msg): # Error codes for nothing to read if err not in [errno.EAGAIN, errno.EWOULDBLOCK, WSAEWOULDBLOCK]: if bytesRead: return bytesRead @@ -178,7 +178,7 @@ def write_some(self): self.connection_lost() return 0 - except socket.error, (err, msg): + except socket.error as (err, msg): # Error codes for write buffer full if err not in [errno.EAGAIN, errno.EWOULDBLOCK, WSAEWOULDBLOCK]: if bytesWritten: return bytesWritten @@ -189,7 +189,7 @@ def write_some(self): def queue_command(self, command): - if debug: print 'command: ' + command + if debug: print ('command: ' + command) self.writeBuf += command + '\n' @@ -199,9 +199,9 @@ def parse_message(self, version, type, data): #if debug: print 'MSG:', type, msg self.messages.append((version, type, msg)) self.last_message = time.time() - except Exception, e: - print 'ERROR parsing PyON message: %s: %s' % ( - str(e), data.encode('string_escape')) + except Exception as e: + print ('ERROR parsing PyON message: %s: %s' + % (str(e), data.encode('string_escape'))) def parse(self): @@ -214,8 +214,7 @@ def parse(self): if len(tokens) < 3: self.readBuf = self.readBuf[eol:] - raise Exception, 'Invalid PyON line: ' + \ - line.encode('string_escape') + raise Exception('Invalid PyON line: ' + line.encode('string_escape')) version = int(tokens[1]) type = tokens[2] @@ -248,21 +247,20 @@ def update(self): while self.parse(): continue # Handle special case for OSX disconnect - except socket.error, e: + except socket.error as e: if sys.platform == 'darwin' and e.errno == errno.EPIPE: self.fail_reason = 'refused' self.close() else: raise - except Exception, e: - print 'ERROR on connection to %s:%d: %s' % ( - self.address, self.port, e) + except Exception as e: + print ('ERROR on connection to %s:%d: %s' % (self.address, self.port, e)) # Timeout connection if self.connected and self.last_message and \ self.last_message + 10 < time.time(): - print 'Connection timed out' + print ('Connection timed out') self.close() @@ -277,7 +275,7 @@ def update(self): conn.update() for version, type, data in conn.messages: - print 'PyON %d %s:\n' % (version, type), data + print ('PyON %d %s:\n' % (version, type), data) conn.messages = [] time.sleep(0.1) diff --git a/fah/FAHControl.py b/fah/FAHControl.py index 437562b5..f26c9159 100644 --- a/fah/FAHControl.py +++ b/fah/FAHControl.py @@ -17,7 +17,7 @@ ''' import sys -import os +import time import re import traceback import platform @@ -75,8 +75,8 @@ def osx_version(): if sys.platform != 'darwin': return None try: ver = tuple([int(x) for x in platform.mac_ver()[0].split('.')]) - except Exception, e: - print e + except Exception as e: + print (e) darwin_ver = platform.release().split('.') ver = (10, int(darwin_ver[0]) - 4, int(darwin_ver[1])) return ver @@ -100,7 +100,8 @@ def applicationShouldHandleReopen_hasVisibleWindows_(self, app, flag): applicationShouldHandleReopen_hasVisibleWindows_, signature = sig1) ]) - except Exception, e: print e + except Exception as e: + print (e) def osx_accel_window_close(accel_group, acceleratable, keyval, modifier): @@ -170,8 +171,8 @@ def __init__(self, glade = 'FAHControl.glade'): try: self.db = load_fahcontrol_db() - except Exception, e: - print e + except Exception as e: + print (e) sys.exit(1) # OSX integration @@ -537,7 +538,8 @@ def run(self): ag.connect_group(key, mod, gtk.ACCEL_VISIBLE, osx_accel_window_minimize) self.window.add_accel_group(ag) - except Exception, e: print e + except Exception as e: + print (e) gtk.main() @@ -600,8 +602,8 @@ def osx_window_focus_workaround(self): cmd = ['/usr/bin/osascript', '-e', 'tell app "FAHControl" to reopen'] try: subprocess.Popen(cmd) - except Exception, e: - print e, ':', ' '.join(cmd) + except Exception as e: + print (e, ':', ' '.join(cmd)) def connect_option_cell(self, name, model, col): @@ -706,7 +708,8 @@ def quit(self): try: self.db.flush_queued() - except Exception, e: print e + except Exception as e: + print (e) sys.exit(0) # Force shutdown @@ -738,7 +741,7 @@ def app_should_block_terminate(self, app): def load_theme(self, theme): for name, rc in self.theme_list: if theme == name: - print 'Loading theme', theme + print ('Loading theme %r' % theme) settings = gtk.settings_get_default() @@ -841,7 +844,7 @@ def preferences_load(self): elif name == 'team_stats': value = '' elif name == 'donor_stats_link': value = 'Folding@home' elif name == 'team_stats_link': value = 'Folding@home' - else: raise Exception, 'Unknown preference widget "%s"' % name + else: raise Exception('Unknown preference widget "%s"' % name) if value is not None: set_widget_str_value(widget, value) @@ -946,7 +949,8 @@ def update_client_list(self): self.client_list.set(iter, i, row[i]) self.client_list.row_changed(path, iter) iter = self.client_list.iter_next(iter) - except Exception, e: print e + except Exception as e: + print (e) return False # no timer repeat @@ -964,7 +968,7 @@ def resort_client_list(self): name = client.name i = ibyname_old.get(name) if i is None: - print 'unable to resort client list: unknown name %s' % name + print ('unable to resort client list: unknown name %s' % name) return new_order.append(i) self.client_list.reorder(new_order) @@ -1239,7 +1243,7 @@ def error(self, message, buttons = gtk.BUTTONS_OK, on_response = None, # log to terminal window if sys.exc_info()[2]: traceback.print_exc() - print 'ERROR:', message + print ('ERROR: %s' % message) # Don't open more than one if self.error_dialog is not None: return False @@ -1346,7 +1350,7 @@ def on_viewer(self, widget, data = None): if slot is not None: cmd.append('--slot=%d' % slot.id) debug = True - if debug: print cmd + if debug: print (cmd) try: if sys.platform == 'darwin': @@ -1354,7 +1358,7 @@ def on_viewer(self, widget, data = None): bufsize = 4096, stderr=subprocess.PIPE) else: self.viewer = subprocess.Popen(cmd, cwd = get_home_dir()) - except Exception, e: + except Exception: self.error('Failed to launch viewer with command:\n\n' + ' '.join(cmd)) @@ -1388,7 +1392,7 @@ def on_window_delete(self, widget, event, data = None): def on_window_is_active(self, window, *args): try: if window.is_active(): self.update_client_list() - except Exception, e: print e + except Exception as e: print (e) # Preferences signals diff --git a/fah/util/SingleApp.py b/fah/util/SingleApp.py index b89ec4b1..22de09de 100644 --- a/fah/util/SingleApp.py +++ b/fah/util/SingleApp.py @@ -70,7 +70,7 @@ def check_for_instance(self): sock.connect(single_app_addr) sock.send('PING') if sock.recv(1024).strip() == 'OK': - print 'Already running' + print ('Already running') sys.exit(1) except socket.error: diff --git a/fah/util/__init__.py b/fah/util/__init__.py index 8937929f..4e3fed35 100644 --- a/fah/util/__init__.py +++ b/fah/util/__init__.py @@ -113,7 +113,7 @@ def get_widget_str_value(widget): return widget.get_active_text() else: - print 'ERROR: unsupported widget type %s' % type(widget) + print ('ERROR: unsupported widget type %s' % type(widget)) def set_widget_str_value(widget, value): @@ -147,7 +147,7 @@ def set_widget_str_value(widget, value): widget.set_active(i) return - print 'ERROR: Invalid value "%s"' % value + print ('ERROR: Invalid value "%s"' % value) elif isinstance(widget, gtk.ProgressBar): widget.set_text(value) @@ -160,7 +160,7 @@ def set_widget_str_value(widget, value): widget.set_fraction(fraction) else: - print 'ERROR: unsupported option widget type %s' % type(widget) + print ('ERROR: unsupported option widget type %s' % type(widget)) def set_widget_change_action(widget, action): @@ -180,7 +180,7 @@ def set_widget_change_action(widget, action): widget.connect('rows_reordered', action) else: - print 'ERROR: unsupported option widget type %s' % type(widget) + print ('ERROR: unsupported option widget type %s' % type(widget)) def get_home_dir(): diff --git a/setup.py b/setup.py index e498c4fe..8c176630 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ dir = os.path.dirname(inspect.getfile(inspect.currentframe())) if dir == '': dir = '.' -print 'dir =', dir +print ('dir = %s' % dir) os.chdir(dir) From 346c2cb9b432c30532cfd0d060955027ee7d0cc6 Mon Sep 17 00:00:00 2001 From: "J. Borovec" Date: Thu, 12 Mar 2020 14:53:36 +0100 Subject: [PATCH 2/2] fix raise Exception --- fah/FAHControl.py | 6 +++--- fah/SlotConfig.py | 4 ++-- fah/db/Database.py | 7 +++---- fah/db/Table.py | 5 ++--- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/fah/FAHControl.py b/fah/FAHControl.py index f26c9159..9eacc896 100644 --- a/fah/FAHControl.py +++ b/fah/FAHControl.py @@ -1032,15 +1032,15 @@ def save_client_config(self, client): # Validate passkey if not self.passkey_validator.is_good(): - raise Exception, 'Passkey is invalid' + raise Exception('Passkey is invalid') # Validate password if not self.password_validator.is_good(): - raise Exception, 'Client password is invalid' + raise Exception('Client password is invalid') # Validate proxy password if not self.proxy_pass_validator.is_good(): - raise Exception, 'Proxy password is invalid' + raise Exception('Proxy password is invalid') self.deactivate_client() diff --git a/fah/SlotConfig.py b/fah/SlotConfig.py index 56f3552f..4a77c414 100644 --- a/fah/SlotConfig.py +++ b/fah/SlotConfig.py @@ -42,7 +42,7 @@ def __init__( # Type if self.description.startswith('cpu'): self.type = 'cpu' elif self.description.startswith('gpu'): self.type = 'gpu' - else: raise Exception, 'Invalid slot type "%s"' % description + else: raise Exception('Invalid slot type "%s"' % description) def add_to_ui(self, app): @@ -94,7 +94,7 @@ def load_dialog(self, app): # Type if self.type == 'cpu': app.slot_type_cpu.set_active(True) elif self.type == 'gpu': app.slot_type_gpu.set_active(True) - else: raise Exception, 'Invalid slot type "%s"' % self.type + else: raise Exception('Invalid slot type "%s"' % self.type) used.add('gpu') # SMP diff --git a/fah/db/Database.py b/fah/db/Database.py index c586fc20..6bafbf4d 100644 --- a/fah/db/Database.py +++ b/fah/db/Database.py @@ -52,7 +52,7 @@ def get_table(self, name): for table in self.tables: if table.name == name: return table - raise Exception, 'Table "%s" not found' % name + raise Exception('Table "%s" not found' % name) def get_version(self): @@ -152,9 +152,8 @@ def create(self): def validate(self): current = self.get_current_version() if self.get_version() < current: - raise Exception, \ - ('Configuration database "%s" version %d is newer than is ' - 'supported %d') % (self.filename, current, self.get_version()) + raise Exception('Configuration database "%s" version %d is newer than is supported %d' + % (self.filename, current, self.get_version())) elif self.get_version() != current: # Create or upgrade DB diff --git a/fah/db/Table.py b/fah/db/Table.py index ebbffc7f..3555a5d1 100644 --- a/fah/db/Table.py +++ b/fah/db/Table.py @@ -57,8 +57,8 @@ def insert(self, db, **kwargs): if len(cols) != len(kwargs): col_names = set(map(Column.get_name, cols)) missing = filter(lambda kw: not kw in col_names, kwargs.keys()) - raise Exception, 'Table %s does not have column(s) %s' % ( - self.name, ', '.join(missing)) + raise Exception('Table %s does not have column(s) %s' + % (self.name, ', '.join(missing))) sql = 'REPLACE INTO "%s" ("%s") VALUES (%s)' % ( self.name, '","'.join(map(Column.get_name, cols)), @@ -66,7 +66,6 @@ def insert(self, db, **kwargs): db.execute(sql).close() - def select(self, db, cols = None, **kwargs): if cols is None: cols = '"' + '","'.join(map(str, self.cols)) + '"'