From c68c74c9ab65cfc644ed7ef51c3b4fa4b9143ae6 Mon Sep 17 00:00:00 2001 From: Dmitry Shachnev Date: Fri, 26 Sep 2014 16:35:49 +0400 Subject: [PATCH] invest-applet: Do not use deprecated Python 2 syntax This syntax is not supported in Python 3, so we need to remove it before porting. - Use print() function. - Use 'except ... as ...' syntax. - Use 'foo in dict' syntax. - Use absolute imports. - Use new syntax for octal numbers. This commit is based on running 'futurize -1' command. --- invest-applet/invest/__init__.py | 19 +++++++------- invest-applet/invest/about.py | 2 +- invest-applet/invest/chart.py | 4 +-- invest-applet/invest/invest-applet.py | 6 ++--- invest-applet/invest/preferences.py | 23 +++++++++-------- invest-applet/invest/quotes.py | 47 ++++++++++++++++++----------------- invest-applet/invest/test.py | 5 ++-- invest-applet/invest/widgets.py | 4 +-- 8 files changed, 57 insertions(+), 53 deletions(-) diff --git a/invest-applet/invest/__init__.py b/invest-applet/invest/__init__.py index cc3ecca..24fc882 100644 --- a/invest-applet/invest/__init__.py +++ b/invest-applet/invest/__init__.py @@ -1,10 +1,11 @@ +from __future__ import absolute_import import os, sys, traceback from os.path import join, exists, isdir, isfile, dirname, abspath, expanduser from types import ListType import datetime from gi.repository import GObject, Gtk, Gdk, Gio import cPickle -import networkmanager +from . import networkmanager # Autotools set the actual data_dir in defs.py from defs import * @@ -14,10 +15,10 @@ DEBUGGING = False # central debugging and error method def debug(msg): if DEBUGGING: - print "%s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), msg) + print("%s: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), msg)) def error(msg): - print "%s: ERROR: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), msg) + print("%s: ERROR: %s" % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), msg)) def exceptionhandler(t, value, tb): @@ -54,8 +55,8 @@ else: USER_INVEST_DIR = expanduser("~/.config/gnome-applets/invest-applet") if not exists(USER_INVEST_DIR): try: - os.makedirs(USER_INVEST_DIR, 0744) - except Exception , msg: + os.makedirs(USER_INVEST_DIR, 0o744) + except Exception as msg: error('Could not create user dir (%s): %s' % (USER_INVEST_DIR, msg)) # ------------------------------------------------------------------------------ @@ -95,7 +96,7 @@ def exchangeless_stock_format(stocks): purchases = stocks[symbol]["purchases"] if len(purchases) > 0: purchase = purchases[0] - if not purchase.has_key("exchange"): + if "exchange" not in purchase: return True return False @@ -138,7 +139,7 @@ try: # here, stocks is a most up-to-date dict, but we need it to be a list STOCKS = update_to_list_stock_format(STOCKS) -except Exception, msg: +except Exception as msg: error("Could not load the stocks from %s: %s" % (STOCKS_FILE, msg) ) STOCKS = [] @@ -163,7 +164,7 @@ except Exception, msg: CONFIG_FILE = join(USER_INVEST_DIR, "config.pickle") try: CONFIG = cPickle.load(file(CONFIG_FILE)) -except Exception, msg: +except Exception as msg: error("Could not load the configuration from %s: %s" % (CONFIG_FILE, msg) ) CONFIG = {} # default configuration @@ -209,7 +210,7 @@ def get_gnome_proxy(): # proxy config found, memorize PROXY = {'http': url} - except Exception, msg: + except Exception as msg: error("Failed to get proxy configuration from GSettings:\n%s" % msg) # use gsettings to get proxy config diff --git a/invest-applet/invest/about.py b/invest-applet/invest/about.py index 4dfddfa..7f85921 100644 --- a/invest-applet/invest/about.py +++ b/invest-applet/invest/about.py @@ -8,7 +8,7 @@ from gi.repository import Gtk, Gdk, GdkPixbuf invest_logo = None try: invest_logo = GdkPixbuf.Pixbuf.new_from_file_at_size(join(invest.ART_DATA_DIR, "invest_neutral.svg"), 96, 96) -except Exception, msg: +except Exception as msg: pass def show_about(): diff --git a/invest-applet/invest/chart.py b/invest-applet/invest/chart.py index b76128c..9da45e9 100644 --- a/invest-applet/invest/chart.py +++ b/invest-applet/invest/chart.py @@ -48,7 +48,7 @@ class ImageRetriever(Thread, _IdleObject): def run(self): self.image = Gtk.Image() try: sock = urllib.urlopen(self.image_url, proxies = invest.PROXY) - except Exception, msg: + except Exception as msg: invest.debug("Error while opening %s: %s" % (self.image_url, msg)) else: loader = GdkPixbuf.PixbufLoader() @@ -114,7 +114,7 @@ class FinancialChart: try: pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(join(invest.ART_DATA_DIR, "invest_neutral.svg"), 96,96) self.ui.get_object("plot").set_from_pixbuf(pixbuf) - except Exception, msg: + except Exception as msg: invest.debug("Could not load 'invest-neutral.svg' file: %s" % msg) pass diff --git a/invest-applet/invest/invest-applet.py b/invest-applet/invest/invest-applet.py index f7fb2fc..dd68235 100755 --- a/invest-applet/invest/invest-applet.py +++ b/invest-applet/invest/invest-applet.py @@ -10,7 +10,7 @@ def _check(path): name = join(dirname(__file__), '..') if _check(name): - print 'Running uninstalled invest, modifying PYTHONPATH' + print('Running uninstalled invest, modifying PYTHONPATH') sys.path.insert(0, abspath(name)) else: sys.path.insert(0, abspath("@PYTHONDIR@")) @@ -40,7 +40,7 @@ def applet_factory(applet, iid, data): def usage(): - print """=== Invest applet: Usage + print("""=== Invest applet: Usage $ invest-applet [OPTIONS] OPTIONS: @@ -54,7 +54,7 @@ and executing the panel-applet-test application: Click 'execute'. Make sure no invest applet is currently running in the panel. If invest is not installed to the system, instead execute env GNOME_PANEL_APPLETS_DIR=/PATH/TO/INVEST_SOURCES/data panel-test-applets - """ + """) sys.exit() if __name__ == "__main__": diff --git a/invest-applet/invest/preferences.py b/invest-applet/invest/preferences.py index 7bc30d1..23ffad1 100644 --- a/invest-applet/invest/preferences.py +++ b/invest-applet/invest/preferences.py @@ -1,9 +1,10 @@ +from __future__ import absolute_import from gettext import gettext as _ import locale from os.path import join from gi.repository import GObject, Gtk import invest -import currencies +from . import currencies import cPickle class PrefsDialog: @@ -17,13 +18,13 @@ class PrefsDialog: self.currency_code = None self.currencies = currencies.Currencies.currencies self.indexexpansion = self.ui.get_object("indexexpansion") - if invest.CONFIG.has_key('indexexpansion'): + if 'indexexpansion' in invest.CONFIG: self.indexexpansion.set_active(invest.CONFIG['indexexpansion']) else: self.indexexpansion.set_active(False) self.hidecharts = self.ui.get_object("hidecharts") - if invest.CONFIG.has_key('hidecharts'): + if 'hidecharts' in invest.CONFIG: self.hidecharts.set_active(invest.CONFIG['hidecharts']) else: self.hidecharts.set_active(False) @@ -57,9 +58,9 @@ class PrefsDialog: completion.set_match_func(self.match_func, 0) completion.connect("match-selected", self.on_completion_selection, 1) - if invest.CONFIG.has_key("currency"): + if "currency" in invest.CONFIG: code = invest.CONFIG["currency"]; - if self.currencies.has_key(code): + if code in self.currencies: self.currency_code = code; currency = self.format_currency(self.currencies[self.currency_code], self.currency_code) self.currency.set_text(currency) @@ -91,7 +92,7 @@ class PrefsDialog: else: value = locale.atof(new_text) self.model[path][col] = value - except Exception, msg: + except Exception as msg: invest.error('Exception while processing cell change: %s' % msg) pass @@ -164,7 +165,7 @@ class PrefsDialog: try: cPickle.dump(invest.STOCKS, file(invest.STOCKS_FILE, 'w')) invest.debug('Stocks written to file') - except Exception, msg: + except Exception as msg: invest.error('Could not save stocks file: %s' % msg) # store the CONFIG (currency, index expansion) into the config file @@ -176,7 +177,7 @@ class PrefsDialog: try: cPickle.dump(invest.CONFIG, file(invest.CONFIG_FILE, 'w')) invest.debug('Configuration written to file') - except Exception, msg: + except Exception as msg: invest.debug('Could not save configuration file: %s' % msg) @@ -212,7 +213,7 @@ class PrefsDialog: def add_to_store(self, store, parent, stocks): for stock in stocks: - if not stock.has_key('ticker'): + if 'ticker' not in stock: name = stock['name'] list = stock['list'] row = store.append(parent, [name, None, None, None, None, None]) @@ -222,7 +223,7 @@ class PrefsDialog: label = stock["label"] purchases = stock["purchases"] for purchase in purchases: - if purchase.has_key("exchange"): + if "exchange" in purchase: exchange = purchase["exchange"] else: exchange = 0.0 @@ -327,7 +328,7 @@ class PrefsDialog: # if it is a currency code, take that one if len(text) == 3: # try to find the string as code - if self.currencies.has_key(text): + if text in self.currencies: self.pick_currency(text) return else: diff --git a/invest-applet/invest/quotes.py b/invest-applet/invest/quotes.py index e441838..c93f0e4 100644 --- a/invest-applet/invest/quotes.py +++ b/invest-applet/invest/quotes.py @@ -1,3 +1,4 @@ +from __future__ import absolute_import from os.path import join, getmtime from gi.repository import GObject, Gtk, Gdk, GdkPixbuf, PanelApplet from gettext import gettext as _ @@ -9,7 +10,7 @@ from threading import Thread from os import listdir, unlink import re import invest, invest.about, invest.chart -import currencies +from . import currencies # TODO: start currency retrieval after _all_ index expansion completed !!! @@ -62,7 +63,7 @@ class QuotesRetriever(Thread, _IdleObject): quotes_file = urlopen(quotes_url, proxies = invest.PROXY) self.data = quotes_file.read () quotes_file.close () - except Exception, msg: + except Exception as msg: invest.debug("Error while retrieving quotes data (url = %s): %s" % (quotes_url, msg)) else: self.retrieved = True @@ -101,7 +102,7 @@ class QuoteUpdater(Gtk.TreeStore): self.updated = True self.last_updated = datetime.datetime.fromtimestamp(getmtime(invest.QUOTES_FILE)) self.update_tooltip() - except Exception, msg: + except Exception as msg: invest.error("Could not load the cached quotes file %s: %s" % (invest.QUOTES_FILE, msg) ) # stores the csv content on disk so it can be used on next start up @@ -111,13 +112,13 @@ class QuoteUpdater(Gtk.TreeStore): f = open(invest.QUOTES_FILE, 'w') f.write(data) f.close() - except Exception, msg: + except Exception as msg: invest.error("Could not save the retrieved quotes file to %s: %s" % (invest.QUOTES_FILE, msg) ) def expand_indices(self): - if not ( invest.CONFIG.has_key('indexexpansion') and invest.CONFIG['indexexpansion'] ): + if not ( 'indexexpansion' in invest.CONFIG and invest.CONFIG['indexexpansion'] ): # retrieve currencies immediately self.retrieve_currencies() return @@ -145,7 +146,7 @@ class QuoteUpdater(Gtk.TreeStore): f = open(filename, 'w') f.write(data) f.close() - except Exception, msg: + except Exception as msg: invest.error("Could not save the retrieved index quotes file of %s to %s: %s" % (index, filename, msg) ) return @@ -157,7 +158,7 @@ class QuoteUpdater(Gtk.TreeStore): f = open(filename, 'r') data = f.readlines() f.close() - except Exception, msg: + except Exception as msg: invest.error("Could not load index quotes file %s of index %s: %s" % (filename, index, msg) ) return @@ -165,7 +166,7 @@ class QuoteUpdater(Gtk.TreeStore): self.expand_index(index, data) def load_all_index_quotes(self): - if not ( invest.CONFIG.has_key('indexexpansion') and invest.CONFIG['indexexpansion'] ): + if not ( 'indexexpansion' in invest.CONFIG and invest.CONFIG['indexexpansion'] ): return # load all existing index quotes files @@ -242,7 +243,7 @@ class QuoteUpdater(Gtk.TreeStore): def get_tickers(self, stocks): tickers = [] for stock in stocks: - if stock.has_key('ticker'): + if 'ticker' in stock: ticker = stock['ticker'] tickers.append(ticker) else: @@ -252,7 +253,7 @@ class QuoteUpdater(Gtk.TreeStore): def get_indices(self, stocks): indices = [] for stock in stocks: - if stock.has_key('ticker'): + if 'ticker' in stock: ticker = stock['ticker'] if ticker.startswith('^'): indices.append(ticker) @@ -306,7 +307,7 @@ class QuoteUpdater(Gtk.TreeStore): f = open(invest.CURRENCIES_FILE, 'w') f.write(data) f.close() - except Exception, msg: + except Exception as msg: invest.error("Could not save the retrieved currencies to %s: %s" % (invest.CURRENCIES_FILE, msg) ) def load_currencies(self): @@ -317,7 +318,7 @@ class QuoteUpdater(Gtk.TreeStore): f.close() self.convert_currencies(self.parse_yahoo_csv(csv.reader(data))) - except Exception, msg: + except Exception as msg: invest.error("Could not load the currencies from %s: %s" % (invest.CURRENCIES_FILE, msg) ) def update_tooltip(self, msg = None): @@ -434,7 +435,7 @@ class QuoteUpdater(Gtk.TreeStore): # mark quotes to finally be valid self.quotes_valid = True - except Exception, msg: + except Exception as msg: invest.debug("Failed to populate quotes: %s" % msg) invest.debug(quotes) self.quotes_valid = False @@ -442,7 +443,7 @@ class QuoteUpdater(Gtk.TreeStore): def retrieve_currencies(self): # start retrieving currency conversion rates - if invest.CONFIG.has_key("currency"): + if "currency" in invest.CONFIG: target_currency = invest.CONFIG["currency"] symbols = [] @@ -464,7 +465,7 @@ class QuoteUpdater(Gtk.TreeStore): def add_quotes(self, quotes, stocks, parent): for stock in stocks: - if not stock.has_key('ticker'): + if 'ticker' not in stock: name = stock['name'] list = stock['list'] # here, the stock group name is used as the label, @@ -472,13 +473,13 @@ class QuoteUpdater(Gtk.TreeStore): # in preferences, the label == None indicates this try: row = self.insert(parent, 0, [None, name, None, True, None, None, None, None, None]) - except Exception, msg: + except Exception as msg: invest.debug("Failed to insert group %s: %s" % (name, msg)) self.add_quotes(quotes, list, row) # Todo: update the summary statistics of row else: ticker = stock['ticker']; - if not quotes.has_key(ticker): + if ticker not in quotes: invest.debug("no quote for %s retrieved" % ticker) continue @@ -501,7 +502,7 @@ class QuoteUpdater(Gtk.TreeStore): (balance, change) = self.balance(stock["purchases"], quote["trade"]) row = self.insert(parent, 0, [ticker, label, quote["currency"], False, float(balance), float(change), float(quote["trade"]), float(quote["variation_pct"]), None]) self.add_balance_change(balance, change, quote["currency"]) - except Exception, msg: + except Exception as msg: invest.debug("Failed to insert stock %s: %s" % (stock, msg)) self.quotes_change += quote['variation_pct'] @@ -510,7 +511,7 @@ class QuoteUpdater(Gtk.TreeStore): self.retrieve_image(ticker, row) def retrieve_image(self, ticker, row): - if invest.CONFIG.has_key('hidecharts') and invest.CONFIG['hidecharts']: + if 'hidecharts' in invest.CONFIG and invest.CONFIG['hidecharts']: return url = 'http://ichart.yahoo.com/h?s=%s' % ticker @@ -547,7 +548,7 @@ class QuoteUpdater(Gtk.TreeStore): def convert_currencies(self, quotes): # if there is no target currency, this method should never have been called - if not invest.CONFIG.has_key("currency"): + if "currency" not in invest.CONFIG: return # reset the overall balance @@ -573,7 +574,7 @@ class QuoteUpdater(Gtk.TreeStore): # and only convert stocks that are not in the target currency # and if we have a conversion rate if not ( len(symbol) == 8 and symbol[6:8] == "=X" ) and \ - currency != target_currency and rates.has_key(currency): + currency != target_currency and currency in rates: # first convert the balance, it needs the original value if not self.get_value(iter, self.TICKER_ONLY): ticker = self.get_value(iter, self.SYMBOL) @@ -601,7 +602,7 @@ class QuoteUpdater(Gtk.TreeStore): if balance == 0 and change == 0: return - if self.statistics.has_key(currency): + if currency in self.statistics: self.statistics[currency]["balance"] += balance self.statistics[currency]["paid"] += balance/change*100 else: @@ -613,7 +614,7 @@ class QuoteUpdater(Gtk.TreeStore): # check if we have only simple quotes def simple_quotes_only(self, stocks): for stock in stocks: - if stock.has_key('purchases'): + if 'purchases' in stock: if not self.is_simple_quote(stock): return False else: diff --git a/invest-applet/invest/test.py b/invest-applet/invest/test.py index 6674c4c..ebd8250 100755 --- a/invest-applet/invest/test.py +++ b/invest-applet/invest/test.py @@ -1,14 +1,15 @@ #!/usr/bin/python +from __future__ import absolute_import import unittest from os.path import * import sys # Make sure we run the local version sys.path.insert(0, abspath(dirname(__file__) + "/..")) -print sys.path +print(sys.path) -import quotes +from . import quotes import invest def null_function (*args): diff --git a/invest-applet/invest/widgets.py b/invest-applet/invest/widgets.py index 1721c26..e4fe590 100644 --- a/invest-applet/invest/widgets.py +++ b/invest-applet/invest/widgets.py @@ -66,7 +66,7 @@ class InvestWidget(Gtk.TreeView): column.set_cell_data_func(cell, col_cellgetdata_functions[i]) self.append_column(column) elif i == 3: - if invest.CONFIG.has_key('hidecharts') and invest.CONFIG['hidecharts']: + if 'hidecharts' in invest.CONFIG and invest.CONFIG['hidecharts']: continue cell_pb = Gtk.CellRendererPixbuf() column = Gtk.TreeViewColumn (col_name, cell_pb, pixbuf=quotes_updater.PB) @@ -233,7 +233,7 @@ class InvestTrend(Gtk.Image): self.pixbuf.fill( int(color.red*factor)<<24|int(color.green*factor)<<16|int(color.blue*factor)<<8|opacity) self.set_from_pixbuf(self.pixbuf) - except Exception, msg: + except Exception as msg: invest.error("Could not set color: %s" % msg) def on_quotes_update(self, updater): -- 2.1.1