def main(): parser = argparse.ArgumentParser() parser.add_argument("--nintendont", help="Connect to the given IP via the Nintendont protocol instead.") args = parser.parse_args() app = QCoreApplication(sys.argv) os.environ['QT_API'] = "PySide2" import qasync loop = qasync.QEventLoop(app) asyncio.set_event_loop(loop) logging.config.dictConfig({ 'version': 1, 'formatters': { 'default': { 'format': '[%(asctime)s] [%(levelname)s] [%(name)s] %(funcName)s: %(message)s', } }, 'handlers': { 'default': { 'level': 'DEBUG', 'formatter': 'default', 'class': 'logging.StreamHandler', 'stream': 'ext://sys.stdout', # Default is stderr }, }, 'loggers': { }, 'root': { 'level': 'DEBUG', 'handlers': ['default'], }, }) def catch_exceptions(t, val, tb): global should_quit should_quit = True old_hook(t, val, tb) def catch_exceptions_async(loop, context): if 'future' in context: future: asyncio.Future = context['future'] logging.exception(context["message"], exc_info=future.exception()) else: logging.critical(str(context)) sys.excepthook = catch_exceptions loop.set_exception_handler(catch_exceptions_async) if args.nintendont is not None: backend = NintendontBackend(args.nintendont) else: backend = DolphinBackend() with loop: try: asyncio.get_event_loop().run_until_complete(worker(app, backend)) finally: app.quit()
def testTypes(self): o = MyBaseObject() o.app = QCoreApplication(sys.argv) o.app.exec_() for e in o.events: self.assertTrue(isinstance(e, MyEvent)) o.app = None
def run(): """ Create launch.json with current PID """ cwd = os.path.dirname(__file__) Path(os.path.join(cwd, '.vscode/')).mkdir(exist_ok=True) launch = { "version": "0.2.0", "configurations": [ { "name" : "Pythonic: Attach", "type" : "python", "request" : "attach", "processId" : os.getpid(), "justMyCode": False, "cwd" : cwd } ] } with open(os.path.join(cwd + '/.vscode/launch.json'), 'w') as file: json.dump(launch, file, indent=4) timer = QTimer() timer.start(500) timer.timeout.connect(lambda : None) app = QCoreApplication(sys.argv) ex = MainWorker(app) ex.start(sys.argv) app.exec_()
def setUp(self): '''Set up resources''' global _core_instance if _core_instance is None: _core_instance = QCoreApplication([]) self.app = _core_instance
def setUpClass(cls): if not QCoreApplication.instance(): QCoreApplication() else: # Undo stack's cleanChanged signals might still be on their way if we're running all Toolbox's tests. # Here they cause trouble because they try to invoke a method in non-existent ToolboxUI object. # To remedy the situation we purge all events from the event queue here. QCoreApplication.removePostedEvents(None)
def test_controller_and_worker_good(self): app = QCoreApplication(sys.argv) controller = Controller() controller.worker.finished.connect(QCoreApplication.quit) with patch.object(controller, "on_worker_result") as on_result: controller.start() app.exec_() self.assertEqual(20, len(on_result.mock_calls))
def testScriptQProperty(self): qapp = QCoreApplication([]) myEngine = QScriptEngine() obj = MyObject() scriptObj = myEngine.newQObject(obj) myEngine.globalObject().setProperty("obj", scriptObj) myEngine.evaluate("obj.x = 42") self.assertEqual(scriptObj.property("x").toInt32(), 42) self.assertEqual(obj.property("x"), 42)
def setUp(self): #Acquire resources self.called = False self.app = QCoreApplication([]) self.socket = QUdpSocket() self.server = QUdpSocket() self.server.bind(QHostAddress(QHostAddress.LocalHost), 45454)
def run(): # Create home path (if not already existing) home_path = Path.home() / 'Pythonic' home_path.mkdir(exist_ok=True) # Create log path (if not already existing) logPath = home_path / 'log' logPath.mkdir(exist_ok=True) # Create directory for executables (if not already existing) execPath = home_path / 'executables' execPath.mkdir(exist_ok=True) # Create directory for vs code configuration (if not already existing) vsCodepath = execPath / '.vscode' vsCodepath.mkdir(exist_ok=True) # Append executables folder to module search path sys.path.append(str(execPath)) """ Create launch.json with current PID in hte libraries installation path """ libPath = os.path.dirname(__file__) Path(os.path.join(libPath, '.vscode/')).mkdir(exist_ok=True) launch = { "version": "0.2.0", "configurations": [{ "name": "Pythonic: Attach", "type": "python", "request": "attach", "justMyCode": False, "connect": { "host": "localhost", "port": 5678 } }] } """ Create launch.json with current PID in the user executables path """ with open(vsCodepath / 'launch.json', 'w') as file: json.dump(launch, file, indent=4) app = QCoreApplication(sys.argv) ex = MainWorker(app) ex.start(sys.argv) app.exec_()
def using_move_to_thread(): app = QCoreApplication([]) objThread = QThread() obj = SomeObject() obj.moveToThread(objThread) obj.finished.connect(objThread.quit) objThread.started.connect(obj.long_running) objThread.finished.connect(app.exit) objThread.start() sys.exit(app.exec_())
def run(): timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) app = QCoreApplication(sys.argv) ex = MainWorker(app) #signal.signal(signal.SIGINT, ex.exitApp) ex.start(sys.argv) app.exec_()
def testBlockingSignal(self): app = QCoreApplication.instance() or QCoreApplication([]) eventloop = QEventLoop() emitter = Emitter() receiver = Receiver(eventloop) emitter.connect(emitter, SIGNAL("signal(int)"), receiver.receive, Qt.BlockingQueuedConnection) emitter.start() retval = eventloop.exec_() emitter.wait(2000) self.assertEqual(retval, 0)
def headless_main(args): """ Executes a project using :class:`QCoreApplication`. Args: args (argparser.Namespace): parsed command line arguments. Returns: int: exit status code; 0 for success, everything else for failure """ application = QCoreApplication(sys.argv) startup_event_type = QEvent.Type(QEvent.registerEventType()) task = ExecuteProject(args, startup_event_type, application) application.postEvent(task, QEvent(startup_event_type)) return application.exec_()
def testQCoreAppChildren(self): #QObject.children() after creating a QCoreApplication # Minimal test: # 1- Create QCoreApp # 2- Create parent and childrens # 3- While keeping the children alive, call parent.children() # 4- Delete parent app = QCoreApplication([]) parent = QObject() children = [QObject(parent) for x in range(25)] # Uncomment the lines below to make the test pass # del children # del child2 del parent # XXX Segfaults here self.assert_(True)
def test_controller_and_worker_better(self): app = QCoreApplication.instance() or QCoreApplication(sys.argv) controller = Controller() controller.worker.finished.connect(QCoreApplication.quit, type=Qt.QueuedConnection) timeout_timer = QTimer(parent=controller) timeout_timer.setInterval(3000) timeout_timer.setSingleShot(True) timeout_timer.timeout.connect(lambda: QCoreApplication.exit(-1)) timeout_timer.start() with patch.object(controller, "on_worker_result") as on_result: controller.start() self.assertEqual(0, app.exec_()) self.assertEqual(20, len(on_result.mock_calls))
def testEmitOutsideThread(self): global thread_run app = QCoreApplication([]) source = Source() thread = ThreadJustConnects(source) QObject.connect(thread, SIGNAL('finished()'), lambda: app.exit(0)) thread.start() while not thread_run: pass source.emit_sig() app.exec_() thread.wait() self.assertTrue(thread.target.called)
def main(): parser = argparse.ArgumentParser() parser.parse_args() app = QCoreApplication(sys.argv) os.environ['QT_API'] = "PySide2" import asyncqt loop = asyncqt.QEventLoop(app) asyncio.set_event_loop(loop) def catch_exceptions(t, val, tb): global should_quit should_quit = True old_hook(t, val, tb) sys.excepthook = catch_exceptions with loop: try: asyncio.get_event_loop().run_until_complete(worker(app)) finally: app.quit()
def setup(): global app # we need a QCoreApplication for the child events app = QCoreApplication.instance() if app is None: app = QCoreApplication()
name=scenario, msg=msg)) if severity == 'ERROR' or msg == 'END': # Stop execution on first error or completed scenario ret = 1 if severity == 'ERROR' else 0 try: pipe_out.send(('All', 'COMMAND', 'END')) except AttributeError: mygui.stop() poller.stop() return ret try: if pipe_out.poll(): cmd = pipe_out.recv() if cmd == 'STOP': mygui.stop() poller.stop() return 0 except AttributeError: pass if __name__ == "__main__": signal.signal(signal.SIGINT, signal.SIG_DFL) udpController = None if '--udp' in sys.argv: # Create UDP Controller with default IP/Port values (127.0.0.1:7755:7756) udpController = tasteUDP() QCoreApplication(sys.argv) sys.exit(runScenario(udpController))
def setUp(self): self.qapp = QCoreApplication.instance() or QCoreApplication()
def startNexT(cfgfile, active, execScripts, execCode, withGui): """ Starts next with the given config file and activates the given application. :param cfgfile: path to config file :param active: active application (if None, the first application in the config will be used) :return: None """ logger.debug("Starting nexxT...") config = Configuration() lcl = QLocale.system() lcl.setNumberOptions(QLocale.c().numberOptions()) QLocale.setDefault(lcl) if withGui: app = QApplication() if QApplication.instance() is None else QApplication.instance() app.setWindowIcon(QIcon(":icons/nexxT.svg")) app.setOrganizationName("nexxT") app.setApplicationName("nexxT") setupGuiServices(config) else: app = QCoreApplication() if QCoreApplication.instance() is None else QCoreApplication.instance() app.setOrganizationName("nexxT") app.setApplicationName("nexxT") setupConsoleServices(config) if cfgfile is not None: ConfigFileLoader.load(config, cfgfile) if withGui: mainWindow = Services.getService("MainWindow") mainWindow.restoreState() mainWindow.show() # the reference will still be held by the service, but here we don't need it anymore del mainWindow if active is not None: config.activate(active) # pylint: disable=unused-variable # need to hold the reference of this until the method is called i2 = MethodInvoker(dict(object=Application, method="initialize", thread=app.thread()), MethodInvoker.IDLE_TASK) # pylint: disable=unused-variable waitForSignal(config.appActivated) if Application.activeApplication.getState() != FilterState.ACTIVE: waitForSignal(Application.activeApplication.stateChanged, lambda s: s == FilterState.ACTIVE) logger.info("done") def cleanup(): logger.debug("cleaning up loaded services") Services.removeAll() logger.debug("cleaning up loaded plugins") for v in ("last_traceback", "last_type", "last_value"): if hasattr(sys, v): del sys.__dict__[v] #PluginManager.singleton().unloadAll() logger.debug("cleaning up complete") code_globals = {} for c in execCode: logger.info("Executing code '%s'", c) # note that exec is used intentionally here to provide the user with scripting posibilities exec(compile(c, "<string>", 'exec'), code_globals) # pylint: disable=exec-used logger.debug("Executing code done") for s in execScripts: logger.info("Executing script '%s'", s) with open(s) as fscript: # note that exec is used intentionally here to provide the user with scripting possibilities exec(compile(fscript.read(), s, 'exec'), code_globals) # pylint: disable=exec-used logger.debug("Executing script done") res = app.exec_() logger.debug("closing config") config.close() cleanup() logger.internal("app.exec_ returned") return res
if "PRIVMSG" in data: ch = data.split(" ")[2][1:] name = data.split("!")[0][1:] print(name) if not name in self.CHANNELS[ch]["first_msg_list"]: self.firstMsgControl(data) self.CHANNELS[ch]["first_msg_list"].append(name) if "!slm" in data: self.sendMessage(ch, "Selam @" + data.split("!")[0][1:]) if "!yargı" in data: self.sendMessage(ch, f"@{ch} başkan yargı dağıtıyor!..") def firstMsgControl(self, data): ch = data.split(" ")[2][1:] name = data.split("!")[0][1:] self.sendMessage(ch, "Hoş geldin @{}".format(name)) def sendMessage(self, channel, message): s = bytes(f"PRIVMSG #{channel} :{message} \r\n", "utf-8") self.write(s) print(s) app = QCoreApplication([]) bot = TwitchBot() app.exec_()
def using_q_thread(): app = QCoreApplication([]) thread = AThread() thread.finished.connect(app.exit) thread.start() sys.exit(app.exec_())
def using_q_runnable(): app = QCoreApplication([]) runnable = Runnable() QThreadPool.globalInstance().start(runnable) sys.exit(app.exec_())
def setUp(self): #Create fixtures self.app = QCoreApplication([])
def setUp(self): self._app = QCoreApplication([]) self._lookup = QDnsLookup(QDnsLookup.ANY, 'www.qt.io') self._lookup.finished.connect(self._finished)
def testQCoreApplicationInstance(self): #Tests QCoreApplication.instance() self.assertEqual(QCoreApplication.instance(), None) app = QCoreApplication([]) self.assertEqual(QCoreApplication.instance(), app)
def setUp(self): self.qapp = QCoreApplication.instance() or QCoreApplication() self.test_qobj = QObject() self.addCleanup(self.release_qt_resources)
def setup(): global app app = QCoreApplication.instance() if app is None: app = QCoreApplication()
def testNoArguments(self): app = QCoreApplication() self.assertIsInstance(app, QCoreApplication)