def check(): """ Checks if the config is suitable. """ if not conf.is_valid(): print("The config is missing or incomplete.") return False conf.load() response = api.api_version() if response.has_error(): print("The server or the API is not reachable.") return False if not api.is_minimum_version(response): print("The version of the wallabag instance is too old.") return False response = api.api_token() if response.has_error(): print(response.error_description) return False print("The config is suitable.") return True
def test_read_yml(self): conf.load('test_resources/conf1.yml') self.assertEqual(conf.get('message'), 'this is yml') self.assertEqual(conf.message, 'this is yml') self.assertEqual(conf.reader.message, 'this is yml') from conf import message as msg self.assertEqual(msg, 'this is yml')
def show(entry_id, colors=True, raw=False, html=False): """ Main function for showing an entry. """ conf.load() try: request = api.api_get_entry(entry_id) __handle_request_error(request) entr = entry.Entry(json.loads(request.response)) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) title = entr.title try: delimiter = "".ljust(os.get_terminal_size().columns, '=') # piped output to file or other process except OSError: delimiter = "\n" article = entr.content if not html: article = html2text(article, colors) output = "{0}\n{1}\n{2}".format(title, delimiter, article) if not raw: output = __format_text(output) print(output)
def delete(entry_id, force=False, quiet=False): """ Main function for deleting wallabag entries. """ conf.load() if not force: try: request = api.api_get_entry(entry_id) __handle_request_error(request) entr = entry.Entry(json.loads(request.response)) print("Do you really wish to delete the following entry?") i = input(entr.title + " [y/N] ") if str.lower(i) not in ["y", "yes"]: exit(0) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) try: request = api.api_delete_entry(entry_id) __handle_request_error(request) if not quiet: print("Entry successfully deleted.") print() exit(0) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1)
def list_entries(custom_quantity=None, filter_read=False, filter_starred=None, oldest=False, trim=True): """ Main function for listing wallabag entries. """ conf.load() quantity = None if custom_quantity is None: try: quantity = os.get_terminal_size().lines - 2 # piped output to file or other process except OSError: quantity = sys.maxsize else: quantity = custom_quantity try: request = api.api_list_entries( quantity, filter_read, filter_starred, oldest) if request.has_error(): print("Error: {0} - {1}".format(request.error_text, request.error_description)) exit(-1) response = json.loads(request.response) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) entries = entry.entrylist(response['_embedded']["items"]) print_entries(entries, trim, (not oldest))
def __init__(self): wx_accel.AutoAcceleratorMixIn.__init__(self) conf.load() self.Bind(EVT_LOG, self.on_log_message) self.Bind(EVT_STATUS, self.on_set_status) self.Bind(wx.EVT_CLOSE, self.on_exit) self.console_commands = set() # Commands from run_console() self.frame_console = wx.py.shell.ShellFrame(parent=self, title=u"%s Console" % conf.Title, size=conf.ConsoleSize) self.frame_console.Bind(wx.EVT_CLOSE, self.on_showhide_console) self.frame_console_shown = False # Init flag console = self.console = self.frame_console.shell if not isinstance(conf.ConsoleHistoryCommands, list): conf.ConsoleHistoryCommands = [] for cmd in conf.ConsoleHistoryCommands: console.addHistory(cmd) console.Bind(wx.EVT_KEY_DOWN, self.on_keydown_console) self.widget_inspector = wx.lib.inspection.InspectionTool() self.CreateStatusBar()
def test_asdict(self): conf.load('test_resources/conf1.yml') d = conf.asdict() self.assertEqual(d.get('key_does_not_exist', None), None) self.assertEqual(d.get('key_does_not_exist', 'some_value'), 'some_value') self.assertEqual(d['message'], 'this is yml')
def run_gui(filenames): """Main GUI program entrance.""" global deferred_logs, deferred_status, window conf.load() # Values in some threads would otherwise not be the same sys.modules["main"].deferred_logs = deferred_logs sys.modules["main"].deferred_status = deferred_status # Create application main window app = wx.App(redirect=True) # stdout and stderr redirected to wx popup window = sys.modules["main"].window = skyperious.MainWindow() app.SetTopWindow(window) # stdout/stderr popup closes with MainWindow # Decorate write to catch printed errors try: sys.stdout.write = support.reporting_write(sys.stdout.write) except: pass # Some debugging support window.console.run("import datetime, os, re, time, sys, wx") window.console.run("# All %s modules:" % conf.Title) window.console.run("import conf, controls, emoticons, export, guibase, " "images, main, searchparser, skypedata, skyperious, " "support, templates, util, wordcloud, workers, " "wx_accel") window.console.run("self = main.window # Application main window instance") log("Started application on %s.", datetime.date.today()) for f in filter(os.path.isfile, filenames): wx.CallAfter(wx.PostEvent, window, skyperious.OpenDatabaseEvent(file=f)) app.MainLoop()
def __init__(self): super().__init__() self.initUI() try: conf.load() except Exception as e: print('load error', str(e)) traceback.print_exc()
def export_entry(entry_id, outputfile=''): """ Main function for exporting an entry. """ conf.load() if outputfile == '': outputfile = 'wallabag_' + entry_id + '.txt' form = 'txt' filemode = 't' x = outputfile.split(".") if len(x) > 1: ext = x[len(x)-1].lower() if ext == 'txt': form = 'txt' filemode = 't' elif ext == 'csv': form = 'csv' filemode = 't' elif ext == 'xml': form = 'xml' filemode = 't' elif ext == 'json': form = 'json' filemode = 't' elif ext == 'pdf': form = 'pdf' filemode = 'b' elif ext == 'epub': form = 'epub' filemode = 't' elif ext == 'mobi': form = 'mobi' filemode = 'b' elif ext == 'azw': form = 'mobi' filemode = 'b' try: if filemode == 't': request = api.api_export_entry(entry_id, form) __handle_request_error(request) output = request.response elif filemode == 'b': request = api.api_export_entry_binary(entry_id, form) output = request except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) filehandler = open(outputfile, 'w' + filemode) filehandler.write(output) filehandler.close()
def add(target_url, title=None, star=False, read=False, quiet=False): """ Main function for adding new entries to the wallabag account. """ conf.load() valid_url = False if not re.compile("(?i)https?:\\/\\/.+").match(target_url): for protocol in "https://", "http://": if api.is_valid_url("{0}{1}".format(protocol, target_url)): target_url = "{0}{1}".format(protocol, target_url) valid_url = True break else: valid_url = api.is_valid_url(target_url) if not valid_url: print("Error: Invalid url.") print() exit(-1) try: request = api.api_entry_exists(target_url) if request.has_error(): print("Error: {0} - {1}".format(request.error_text, request.error_description)) print() exit(-1) response = json.loads(request.response) if response['exists']: if not quiet: print("The url was already saved.") exit(0) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) try: request = api.api_add_entry(target_url, title, star, read) if request.has_error(): print("Error: {0} - {1}".format(request.error_text, request.error_description)) print() exit(-1) else: if not quiet: print("Entry successfully added.") exit(0) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1)
def connect(): """ connect to the appropriate sources """ print "configuration name: ", conf.set_name('lightHead') print "missing configuration entries: ", conf.load() # Will ignore send_msg if not connected return (communication.CommBase(conf.expression_server), communication.CommBase(conf.lightHead_server) )
def load(): config = conf.load() logger = logging.getLogger('main') if 'logging' in config['settings']: level = config['settings']['logging'] if level == 'debug': logger.setLevel(logging.DEBUG) if level == 'info': logger.setLevel(logging.INFO) if level == 'warn': logger.setLevel(logging.WARN) if level == 'error': logger.setLevel(logging.ERROR) else: logger.setLevel(logging.INFO) formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s: %(message)s', datefmt='%d-%m-%Y %I:%M:%S') # Everything <= WARN written to stdout ch1 = logging.StreamHandler(sys.stdout) ch1.setLevel(logging.DEBUG) ch1.addFilter(lambda record: record.levelno <= logging.WARN) ch1.setFormatter(formatter) # Everything == ERROR written to stderr ch2 = logging.StreamHandler(sys.stderr) ch2.setLevel(logging.ERROR) ch2.setFormatter(formatter) logger.addHandler(ch1) logger.addHandler(ch2) return logger
def count_entries(filter_read=False, filter_starred=None): """ Prints the number of entries to the standard output. """ conf.load() try: request = api.api_list_entries( sys.maxsize, filter_read, filter_starred) if request.has_error(): print("Error: {0} - {1}".format(request.error_text, request.error_description)) exit(-1) response = json.loads(request.response) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) print(len(response["_embedded"]["items"]))
def update(entry_id, toggle_read=False, toggle_star=False, new_title=None, quiet=False): """ Main method for updating existing wallabag entries. """ conf.load() read_value = None star_value = None try: request = api.api_get_entry(entry_id) __handle_request_error(request) entr = entry.Entry(json.loads(request.response)) if toggle_read and entr.read: read_value = 0 elif toggle_read and not entr.read: read_value = 1 if toggle_star and entr.starred: star_value = 0 elif toggle_star and not entr.starred: star_value = 1 except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1) try: request = api.api_update_entry(entry_id, new_title, star_value, read_value) __handle_request_error(request) if not quiet: print("Entry successfully updated.") print() exit(0) except api.OAuthException as ex: print("Error: {0}".format(ex.text)) print() exit(-1)
def __init__(self): wx_accel.AutoAcceleratorMixIn.__init__(self) conf.load() self.Bind(EVT_LOG, self.on_log_message) self.Bind(EVT_STATUS, self.on_set_status) self.Bind(wx.EVT_CLOSE, self.on_exit) self.frame_console = wx.py.shell.ShellFrame(parent=self, title=u"%s Console" % conf.Title, size=conf.ConsoleSize) self.frame_console.Bind(wx.EVT_CLOSE, self.on_showhide_console) self.frame_console_shown = False # Init flag console = self.console = self.frame_console.shell if not isinstance(conf.ConsoleHistoryCommands, list): conf.ConsoleHistoryCommands = [] for cmd in conf.ConsoleHistoryCommands: console.addHistory(cmd) console.Bind(wx.EVT_KEY_DOWN, self.on_keydown_console) self.widget_inspector = wx.lib.inspection.InspectionTool() self.CreateStatusBar()
def main(addr_port): if not hasattr(G, "initialized"): try: import conf; missing = conf.load() if missing: fatal('missing configuration entries: %s' % missing) if hasattr(conf, 'DEBUG_MODE') and conf.DEBUG_MODE: # set system-wide logging level import comm; comm.set_default_logging(debug=True) cont = initialize(conf.lightHead_server) G.server.set_listen_timeout(0.001) G.server.start() except conf.LoadException, e: fatal('in file {0[0]}: {0[1]}'.format(e)) except Exception, e: fatal(e)
def run(nogui=False): """Parses command-line arguments and either runs GUI, or a CLI action.""" global is_cli, is_gui_possible, is_verbose if (getattr(sys, 'frozen', False) # Binary application or sys.executable.lower().endswith("pythonw.exe")): sys.stdout = ConsoleWriter(sys.stdout) # Hooks for attaching to sys.stderr = ConsoleWriter(sys.stderr) # a text console if "main" not in sys.modules: # E.g. setuptools install, calling main.run srcdir = os.path.abspath(os.path.dirname(__file__)) if srcdir not in sys.path: sys.path.append(srcdir) sys.modules["main"] = __import__("main") argparser = argparse.ArgumentParser(description=ARGUMENTS["description"]) for arg in ARGUMENTS["arguments"]: names = arg["args"] del arg["args"] argparser.add_argument(*names, **arg) subparsers = argparser.add_subparsers(dest="command") for cmd in ARGUMENTS["commands"]: kwargs = dict((k, cmd[k]) for k in cmd if k in ["help", "description"]) subparser = subparsers.add_parser(cmd["name"], **kwargs) for arg in cmd["arguments"]: kwargs = dict((k, arg[k]) for k in arg if k != "args") subparser.add_argument(*arg["args"], **kwargs) if "nt" == os.name: # Fix Unicode arguments, otherwise converted to ? sys.argv[:] = win32_unicode_argv() argv = sys.argv[1:] if not argv or (argv[0] not in subparsers.choices and argv[0].endswith(".db")): argv[:0] = ["gui"] # argparse hack: force default argument if argv[0] in ("-h", "--help") and len(argv) > 1: argv[:2] = argv[:2][::-1] # Swap "-h option" to "option -h" arguments = argparser.parse_args(argv) if hasattr(arguments, "FILE1") and hasattr(arguments, "FILE2"): arguments.FILE1 = [util.to_unicode(f) for f in arguments.FILE1] arguments.FILE2 = [util.to_unicode(f) for f in arguments.FILE2] arguments.FILE = arguments.FILE1 + arguments.FILE2 if arguments.FILE: # Expand wildcards to actual filenames arguments.FILE = sum([(sorted(glob.glob(f)) if "*" in f else [f]) for f in arguments.FILE], []) arguments.FILE = [util.to_unicode(f) for f in arguments.FILE] if "gui" == arguments.command and (nogui or not is_gui_possible): argparser.print_help() status = None if not nogui: status = ("\n\nwxPython not found. %s graphical program " "will not run." % conf.Title) sys.exit(status) elif "gui" != arguments.command: conf.load() is_cli = sys.modules["main"].is_cli = True is_verbose = sys.modules["main"].is_verbose = arguments.verbose enc = sys.stdout.encoding or locale.getpreferredencoding() or "utf-8" if "nt" == os.name: # Avoid print encoding errors under windows sys.stdout = codecs.getwriter(enc)(sys.stdout, "xmlcharrefreplace") sys.stderr = codecs.getwriter(enc)(sys.stderr, "xmlcharrefreplace") if "diff" == arguments.command: run_diff(*arguments.FILE) elif "merge" == arguments.command: run_merge(arguments.FILE, arguments.output) elif "export" == arguments.command: run_export(arguments.FILE, arguments.type) elif "search" == arguments.command: run_search(arguments.FILE, arguments.QUERY) elif "gui" == arguments.command: run_gui(arguments.FILE)
import conf from generate_session import gen_client if __name__ == '__main__': conf = conf.load() api_id, api_hash = conf['api_id'], conf['api_hash'] app = gen_client(api_id, api_hash) app.connect() chats = [] for d in app.iter_dialogs(): chats.append({ "title": d.chat.first_name or d.chat.title or 'NO TITLE', "id": d.chat.username or d.chat.id or 'NOTHING' }) for ch in sorted(chats, key=lambda k: k['title']): print("{title} -> {id}".format(**ch)) app.disconnect()
def fatal(error): print '*** Fatal Error ***', error import conf; conf.load() if hasattr(conf, 'DEBUG_MODE') and conf.DEBUG_MODE: import traceback; traceback.print_exc() shutdown(G.getCurrentController())
def test_read_yaml(self): conf.load('test_resources/conf2.yaml') self.assertEqual(conf.get('message'), 'this is yml')
def test_read_ini(self): conf.load('test_resources/conf6.ini') self.assertEqual(conf.get('main_section')['message'], 'this is ini')
LOG.debug("set %s"%value) if self.face_conn: self.send_values() def send_values(self, target=None): """Send values to face module""" data = "" for au_values in self.AU_map.itervalues(): for au, val in au_values.iteritems(): data += "AU %i %.3s %f\n" % (au, val, 1) self.face_conn.send_msg(""+data) def affect_to_au(self): """Manage mapping from affective space to AU space""" for s in self.sinks.iteritems(): pass if __name__ == "__main__": missing = conf.load() if missing: print "WARNING: missing configuration entries:", missing try: server = comm.createServer(Affect, AffectClient, conf.conn_affect) except UserWarning, err: comm.LOG.error("FATAL ERROR: %s (%s)", sys.argv[0], err) exit(-1) server.serve_forever() LOG.info("Affect done")
def test_read_yml_from_env_var(self): os.environ['configfile'] = 'test_resources/conf1.yml' conf.load('configfile') self.assertEqual(conf.get('message'), 'this is yml')
def test_warn_if_filename_is_empty(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') conf.load('') assert len(w) == 1 assert 'empty name' in str(w[-1].message)
def test_warn_if_file_cannot_be_parsed_due_to_content(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') conf.load('test_resources/conf5.json') assert len(w) == 1 assert 'failed to parse' in str(w[-1].message)
def test_read_yaml_uppercases(self): conf.load('test_resources/conf3.YaMl') self.assertEqual(conf.get('message'), 'this is yml')
def test_warn_if_file_not_found(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') conf.load('no_way_this_file_exists.yml') assert len(w) == 1 assert 'not found' in str(w[-1].message)
def test_read_default(self): conf.load('test_resources/default_python_conf') self.assertEqual(conf.get('main_section')['message'], 'this is default')
def run(nogui=False): """Parses command-line arguments and either runs GUI, or a CLI action.""" global is_cli, is_gui_possible, is_verbose if (getattr(sys, 'frozen', False) # Binary application or sys.executable.lower().endswith("pythonw.exe")): sys.stdout = ConsoleWriter(sys.stdout) # Hooks for attaching to sys.stderr = ConsoleWriter(sys.stderr) # a text console if "main" not in sys.modules: # E.g. setuptools install, calling main.run srcdir = os.path.abspath(os.path.dirname(__file__)) if srcdir not in sys.path: sys.path.append(srcdir) sys.modules["main"] = __import__("main") argparser = argparse.ArgumentParser(description=ARGUMENTS["description"]) for arg in ARGUMENTS["arguments"]: argparser.add_argument(*arg.pop("args"), **arg) subparsers = argparser.add_subparsers(dest="command") for cmd in ARGUMENTS["commands"]: kwargs = dict((k, cmd[k]) for k in cmd if k in ["help", "description"]) subparser = subparsers.add_parser(cmd["name"], **kwargs) for arg in cmd["arguments"]: kwargs = dict((k, arg[k]) for k in arg if k != "args") subparser.add_argument(*arg["args"], **kwargs) if "nt" == os.name: # Fix Unicode arguments, otherwise converted to ? sys.argv[:] = win32_unicode_argv() argv = sys.argv[1:] if not argv or (argv[0] not in subparsers.choices and argv[0].endswith(".db")): argv[:0] = ["gui"] # argparse hack: force default argument if argv[0] in ("-h", "--help") and len(argv) > 1: argv[:2] = argv[:2][::-1] # Swap "-h option" to "option -h" arguments = argparser.parse_args(argv) if hasattr(arguments, "FILE1") and hasattr(arguments, "FILE2"): arguments.FILE1 = [util.to_unicode(f) for f in arguments.FILE1] arguments.FILE2 = [util.to_unicode(f) for f in arguments.FILE2] arguments.FILE = arguments.FILE1 + arguments.FILE2 if arguments.FILE: # Expand wildcards to actual filenames arguments.FILE = sum([glob.glob(f) if "*" in f else [f] for f in arguments.FILE], []) arguments.FILE = sorted(set(util.to_unicode(f) for f in arguments.FILE)) if "gui" == arguments.command and (nogui or not is_gui_possible): argparser.print_help() status = None if not nogui: status = ("\n\nwxPython not found. %s graphical program " "will not run." % conf.Title) sys.exit(status) elif "gui" != arguments.command: conf.load() is_cli = sys.modules["main"].is_cli = True is_verbose = sys.modules["main"].is_verbose = arguments.verbose # Avoid Unicode errors when printing to console. enc = sys.stdout.encoding or locale.getpreferredencoding() or "utf-8" sys.stdout = codecs.getwriter(enc)(sys.stdout, "xmlcharrefreplace") sys.stderr = codecs.getwriter(enc)(sys.stderr, "xmlcharrefreplace") if "diff" == arguments.command: run_diff(*arguments.FILE) elif "merge" == arguments.command: run_merge(arguments.FILE, arguments.output) elif "export" == arguments.command: run_export(arguments.FILE, arguments.type, arguments.chat, arguments.author, arguments.ask_password) elif "search" == arguments.command: run_search(arguments.FILE, arguments.QUERY) elif "gui" == arguments.command: run_gui(arguments.FILE)
import context import conf import api conf.load() response = api.api_version() print("HTTP Status: " + str(response.http_code)) print("Error: " + str(response.error)) print("Errortext: " + response.error_text) print("Body: " + str(response.response)) if response.is_rersponse_status_ok(): if api.is_minimum_version(response): print("Wallabag API is compatible.") else: print("Unsupported wallabag API.")
continue up_value = coeffs[0] * elapsed + coeffs[1] self.AUs[id][2:] = elapsed, up_value to_update.append((id, up_value)) if self.thread_id != thread.get_ident(): self.threadsafe_start() return to_update try: from face.backend import main except ImportError, e: print print '*** FACE MISCONFIGURATION ***' print 'Make sure the FACE backend link points to your backend!' print 'for your information:', e raise if __name__ == '__main__': conf.name = sys.argv[-1] conf.load() try: server = comm.create_server(FaceServer, FaceClient, conf.conn_face) except UserWarning, err: comm.LOG.error("FATAL ERROR: %s (%s)", sys.argv[0], err) exit(-1) server.serve_forever() LOG.debug("Face server done")
def test_raise_invalid_config(self): with self.assertRaises(Exception): conf.load('test_resources/bad.yaml', raise_exception=True)
def test_read_json(self): conf.load('test_resources/conf4.json') self.assertEqual(conf.get('message'), 'this is json')
def test_noraise_invalid_config(self): conf.load('test_resources/bad.yaml')
def __init__(self): wx.Frame.__init__(self, parent=None, title=conf.Title, size=conf.WindowSize) self.data = {} self.text = None self.text_id = None # ID of currently selected text self.panels_history = [] # In Windows 7 and Vista the wx.media.MediaCtrl fires state change # events unreliably, so cannot use sequential play. self.mc_hack = hasattr(sys, "getwindowsversion") and sys.getwindowsversion()[0] > 5 icons = wx.IconBundle() for s in [-1, 32]: icons.AddIcon(wx.ArtProvider_GetIcon(wx.ART_TICK_MARK, wx.ART_FRAME_ICON, (s, s))) self.SetIcons(icons) panel_frame = wx.lib.sized_controls.SizedPanel(self) panel_frame.SetSizerType("vertical") splitter = self.splitter_main = wx.SplitterWindow(parent=panel_frame, style=wx.BORDER_NONE) splitter.SetSizerProps(expand=True, proportion=1) splitter.SetMinimumPaneSize(1) # Create main panel with text box, buttons, and media control. panel_main = wx.lib.sized_controls.SizedPanel(splitter) panel_main.SetSizerType("vertical") panel_labels = wx.lib.sized_controls.SizedPanel(panel_main) panel_labels.SetSizerProps(expand=True, border=(["top"], 5)) panel_labels.SetSizerType("horizontal") label_text = wx.StaticText(panel_labels, label="&Enter text to speak:") panel_labels.Sizer.AddStretchSpacer() label_help = wx.StaticText(panel_labels, label="Use commas and line breaks to create pauses ") label_help.ForegroundColour = "GRAY" label_help.SetSizerProps(halign="right") text = self.edit_text = wx.TextCtrl(panel_main, size=(-1, 50), style=wx.TE_MULTILINE | wx.TE_RICH2) text.SetSizerProps(expand=True, proportion=1, border=(["left", "right", "bottom"], 3)) gauge = self.gauge = wx.Gauge(panel_main) gauge.SetSizerProps(expand=True) panel_buttons = wx.lib.sized_controls.SizedPanel(panel_main) panel_buttons.SetSizerType("horizontal") panel_buttons.SetSizerProps(expand=True) self.button_go = wx.Button(panel_buttons, label="&Text to speech") panel_buttons.Sizer.AddSpacer(10) label_lang = wx.StaticText(panel_buttons, label="&Language:") label_lang.SetSizerProps(border=(["all"], 0), valign="center") self.list_lang = wx.ComboBox(parent=panel_buttons, choices=[i[1] for i in conf.Languages], style=wx.CB_READONLY) self.list_lang.SetSizerProps(border=(["all"], 0), valign="center") panel_buttons.Sizer.AddStretchSpacer() self.cb_allatonce = wx.CheckBox(parent=panel_buttons, label="Complete audio before playing") self.cb_allatonce.SetSizerProps(halign="right", valign="center") self.cb_allatonce.Show(not self.mc_hack) self.button_save = wx.Button(panel_buttons, label="&Save MP3") gauge.ToolTipString = "Audio data chunks" self.button_save.Enabled = False self.list_lang.Selection = conf.Languages.index(("en", "English")) self.list_lang.ToolTipString = "Choose the speech language" self.cb_allatonce.Value = True self.cb_allatonce.ToolTipString = "Download all audio chunks and merge them before playing anything" mc = self.mediactrl = wx.media.MediaCtrl(panel_main, size=(-1, 70)) mc.ShowPlayerControls(wx.media.MEDIACTRLPLAYERCONTROLS_DEFAULT) mc.SetSizerProps(expand=True) self.text_info = wx.StaticText(panel_main, label=conf.InfoText, style=wx.ALIGN_CENTER) # Create side panel with list of texts, and program information. panel_side = wx.lib.sized_controls.SizedPanel(splitter) panel_side.SetSizerType("vertical") panel_list = self.panel_list = wx.lib.scrolledpanel.ScrolledPanel(panel_side) panel_list.BackgroundColour = "WHITE" panel_list.SetSizerProps(expand=True, proportion=100) panel_list.Sizer = wx.BoxSizer(wx.VERTICAL) panel_side.Sizer.AddStretchSpacer() panel_btm = wx.lib.sized_controls.SizedPanel(panel_side) panel_btm.SetSizerProps(halign="right") panel_btm.SetSizerType("horizontal") panel_btm.Sizer.AddStretchSpacer() self.text_version = wx.StaticText(panel_btm, label=conf.VersionText, style=wx.ALIGN_RIGHT) self.text_version.ForegroundColour = "GRAY" self.text_version.ToolTipString = "Ctrl-shift-doubleclick " "opens Python console." panel_btm.Sizer.Add((10, 5)) self.text_version.SetSizerProps(halign="right") self.link_www = wx.HyperlinkCtrl(panel_btm, id=-1, label="github", url=conf.URLHomepage) self.link_www.ToolTipString = "Go to source code repository " "at %s" % conf.URLHomepage self.link_www.SetSizerProps(halign="right") self.out_queue = Queue.Queue() self.mp3_loader = TextToMP3Loader(self, self.out_queue) self.dialog_save = wx.FileDialog( parent=self, defaultDir=os.getcwd(), style=wx.FD_OVERWRITE_PROMPT | wx.FD_SAVE | wx.RESIZE_BORDER ) self.frame_console = wx.py.shell.ShellFrame(parent=self, title="%s Console" % conf.Title) self.frame_console.SetIcons(icons) self.frame_console.Enabled = False # Flag for first toggle if not self.mc_hack: mc.Bind(wx.media.EVT_MEDIA_LOADED, self.on_media_loaded) mc.Bind(wx.media.EVT_MEDIA_FINISHED, self.on_media_finished) self.Bind(EVT_RESULT, self.on_result_event) self.Bind(wx.EVT_BUTTON, self.on_text_to_speech, self.button_go) self.Bind(wx.EVT_BUTTON, self.on_save_mp3, self.button_save) self.Bind(wx.EVT_CLOSE, lambda evt: self.cleanup()) idfocus = wx.NewId() self.Bind(wx.EVT_MENU, lambda e: self.edit_text.SetFocus(), id=idfocus) ac = wx.AcceleratorTable( [ (wx.ACCEL_ALT, ord("T"), self.button_go.Id), (wx.ACCEL_ALT, ord("S"), self.button_save.Id), (wx.ACCEL_ALT, ord("E"), idfocus), ] ) self.SetAcceleratorTable(ac) self.Bind(wx.EVT_CLOSE, self.on_exit) self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.on_size, splitter) self.frame_console.Bind(wx.EVT_CLOSE, self.on_toggle_console) self.text_version.Bind(wx.EVT_LEFT_DCLICK, self.on_toggle_console) conf.load() if conf.LastText and isinstance(conf.LastText, basestring): self.edit_text.Value = conf.LastText if conf.LastLanguage: index = next((i for i, x in enumerate(conf.Languages) if x[0] == conf.LastLanguage), None) if index is not None: self.list_lang.Selection = index if not 0 <= conf.LastVolume <= 1: conf.LastVolume = 0.5 if conf.WindowPosition and conf.WindowSize: if [-1, -1] != conf.WindowSize: self.Position, self.Size = conf.WindowPosition, conf.WindowSize else: self.Maximize() else: self.Center(wx.HORIZONTAL) self.Position.top = 50 sashPos = 3 * self.Size.width / 4 splitter.SplitVertically(panel_main, panel_side, sashPosition=sashPos) self.Show(True) self.edit_text.SetFocus() self.edit_text.SetInsertionPoint(-1)
def test_warn_if_file_cannot_be_parsed(self): with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') conf.load('test_resources/conf.chuck_norris') assert len(w) == 1 assert 'cannot parse' in str(w[-1].message)
def test_get_default(self): conf.load('test_resources/conf1.yml') self.assertEqual(conf.get('key_does_not_exist'), None) self.assertEqual(conf.get('key_does_not_exist', 'some_value'), 'some_value')