def main(): # initialize application args = get_argparser().parse_args() widget_log_handler = log.init_log(args, "browser") app = QtWidgets.QApplication(["ARTIQ Browser"]) loop = QEventLoop(app) asyncio.set_event_loop(loop) atexit.register(loop.close) datasets_sub = models.LocalModelManager(datasets.Model) datasets_sub.init({}) smgr = state.StateManager(args.db_file) browser = Browser(smgr, datasets_sub, args.browse_root, args.server, args.port) widget_log_handler.callback = browser.log.append_message if os.name == "nt": # HACK: show the main window before creating applets. # Otherwise, the windows of those applets that are in detached # QDockWidgets fail to be embedded. browser.show() smgr.load() smgr.start() atexit_register_coroutine(smgr.stop) if args.select is not None: browser.files.select(args.select) browser.show() loop.run_until_complete(browser.exit_request.wait())
def __init__(self, app, device, baudrate): QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.device = device self.baudrate = baudrate self.app = app self.setupUi(self) self.setWindowTitle('Badgecmd') self.main_loop = QEventLoop(self.app) asyncio.set_event_loop(self.main_loop) self.io = IoSignals() self.proto = BadgeProtocol(self.io) self.serial_coro = None self.awaiting = None self.paused = False # connect all of the signals for method in self.__dir__(): if method.startswith('_when_'): emitter_name, signal_name = method.split('_')[-2:] signal = getattr(getattr(self, emitter_name), signal_name) signal.connect(getattr(self, method))
def __init__(self): self.app = QtWidgets.QApplication([]) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) self.window = QtWidgets.QMainWindow() with open(const.UI_MAIN_WINDOW) as f: uic.loadUi(f, self.window) # bludiště zatím nadefinované rovnou v kódu array = numpy.zeros((15, 20), dtype=numpy.int8) # získáme oblast s posuvníky z Qt Designeru scroll_area = self.window.findChild(QtWidgets.QScrollArea, 'scrollArea') # dáme do ní náš grid self.game = Game(array, self) self.grid = self.game.grid scroll_area.setWidget(self.grid) # získáme paletu vytvořenou v Qt Designeru self.palette = self.window.findChild(QtWidgets.QListWidget, 'palette') self._set_buttons() self._set_list_widget()
def main() -> None: """Application entry point""" # configure logging logging.basicConfig(level=logging.INFO) # create the App ant the event loop app = QGuiApplication(sys.argv + ["--style", QUICK_CONTROLS2_STYLE]) loop = QEventLoop(app) asyncio.set_event_loop(loop) # register custom types register_types() # create the QML engine engine = QQmlApplicationEngine() # set context properties engine.rootContext().setContextProperty("version", VERSION) engine.rootContext().setContextProperty("author", AUTHOR) engine.rootContext().setContextProperty("authorEmail", AUTHOR_EMAIL) engine.rootContext().setContextProperty("projectUrl", URL) # load the main QML file engine.load(MAIN_QML_PATH) # start the event loop with loop: loop.run_forever()
def __init__(self): self.app = QApplication(sys.argv) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) self.config = make_config(os.path.join('config', 'env.json')) self.logger = make_logger(self.config) self.port = self.config['CLIENT']['PORT'] self.host = self.config['CLIENT']['HOST'] self.encode = self.config['CLIENT']['ENCODE'] self.path_img_ab = os.path.join(self.config.root_path, 'app', 'client', 'templates', 'imgs', 'ab.gif') self.path_img_ac = os.path.join(self.config.root_path, 'app', 'client', 'templates', 'imgs', 'ac.gif') self.path_img_ai = os.path.join(self.config.root_path, 'app', 'client', 'templates', 'imgs', 'ai.gif') self.window = MainWindow(self) self.ui = self.window.ui self.ie_dialog = ImageEditorDialog(self.config) self.font = QFont() asyncio.ensure_future(self.check_connection(), loop=self.loop) self.ws = None asyncio.ensure_future(self.listen_server(), loop=self.loop) # TODO тестовые данные пользователей self.display_users() self.db = Db(self.loop, self.config) asyncio.ensure_future(self.db.make_tables(), loop=self.loop) asyncio.ensure_future(self.create_users(), loop=self.loop) asyncio.ensure_future(self.get_user(), loop=self.loop) self.user = None
def main(self): connections = dict() users = dict() # Each client will create a new protocol instance self.ins = ChatServerProtocol(self.db_path, connections, users) # GUI app = Qt.QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # NEW must set the event loop wnd = ServerMonitorWindow(server_instance=self.ins, parsed_args=self.args) wnd.show() with loop: coro = loop.create_server(lambda: self.ins, self.args["addr"], self.args["port"]) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C print('Serving on {}:{}'.format(*server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass server.close() loop.run_until_complete(server.wait_closed()) loop.close()
def start(): app = QApplication(sys.argv) # 将Qt事件循环写到asyncio事件循环里。 # QEventLoop不是Qt原生事件循环, # 是被asyncio重写的事件循环。 eventLoop = QEventLoop(app) asyncio.set_event_loop(eventLoop) try: main = Window() main.show() # 当前音乐的显示信息。 # 因为需要布局之后重新绘制的宽高。 # 这个宽高会在show之后才会改变。 # 需要获取宽,高并嵌入到父窗口里。 main.playWidgets.currentMusic.resize(main.navigation.width(), 64) with eventLoop: eventLoop.run_forever() sys.exit(0) except: logger.error("got some error", exc_info=True)
def main_gui(args: argparse.Namespace): QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # Check environment first from PyQt5.QtWidgets import QMessageBox, QSystemTrayIcon def dialog(message: str) -> None: QMessageBox.critical(None, "VirtScreen", message) if not QSystemTrayIcon.isSystemTrayAvailable(): dialog("Cannot detect system tray on this system.") sys.exit(1) check_env(args, dialog) app.setApplicationName("VirtScreen") app.setWindowIcon(QIcon(ICON_PATH)) os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material" # Register the Python type. Its URI is 'People', it's v1.0 and the type # will be called 'Person' in QML. qmlRegisterType(DisplayProperty, 'VirtScreen.DisplayProperty', 1, 0, 'DisplayProperty') qmlRegisterType(Backend, 'VirtScreen.Backend', 1, 0, 'Backend') qmlRegisterType(Cursor, 'VirtScreen.Cursor', 1, 0, 'Cursor') qmlRegisterType(Network, 'VirtScreen.Network', 1, 0, 'Network') # Create a component factory and load the QML script. engine = QQmlApplicationEngine() engine.load(QUrl(MAIN_QML_PATH)) if not engine.rootObjects(): dialog("Failed to load QML") sys.exit(1) sys.exit(app.exec_()) with loop: loop.run_forever()
class KnechtQT: def __init__(self, args): self.port = args.port self.address = args.listen self.app = None self.window = None self.loop = None def _close_window(self): if self.window: self.window.showNormal() self.window.hide() self.window.close() self.window = None def show_text(self, text, duration=None): if duration is None or duration <= 0: duration = 10 if self.window: self._close_window() try: subprocess.call(['xset', 'dpms', 'force', 'on']) except FileNotFoundError as e: pass label = QLabel() label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) label.setTextFormat(Qt.RichText) label.setWordWrap(True) label.setText('<span style="font-size:100px">%s</span>' % text) self.window = QMainWindow() self.window.setWindowTitle("KnechtQT") self.window.setCentralWidget(label) self.window.showFullScreen() self.loop.call_later(duration, self._close_window) def launch(self): self.app = QApplication([]) self.app.setQuitOnLastWindowClosed(False) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) signal.signal(signal.SIGINT, signal.SIG_DFL) with self.loop: coro = self.loop.create_server(lambda: CommandReceiver(self), self.address, self.port) server = self.loop.run_until_complete(coro) self.loop.run_forever() server.close() loop.run_until_complete(server.wait_closed())
def main() -> int: """ This is the main entry point of the application. We must import packages here, in the function, rather than globally, because the logging subsystem must be set up correctly at the import time. """ import atexit import asyncio import datetime from PyQt5.QtWidgets import QApplication from quamash import QEventLoop from . import data_dir, version, resources from .fuhrer import Fuhrer data_dir.init() # Only the main process will be logging into the file log_file_name = os.path.join( data_dir.LOG_DIR, f'{datetime.datetime.now():%Y%m%d-%H%M%S}-{os.getpid()}.log') file_handler = logging.FileHandler(log_file_name) file_handler.setLevel(LOGGING_LEVEL) file_handler.setFormatter( logging.Formatter( '%(asctime)s pid=%(process)-5d %(levelname)-8s %(name)s: %(message)s' )) logging.root.addHandler(file_handler) if '--profile' in sys.argv: try: # noinspection PyPep8Naming import cProfile as profile except ImportError: import profile def save_profile(): prof.disable() prof.dump_stats(log_file_name.replace('.log', '.pstat')) prof = profile.Profile() atexit.register(save_profile) prof.enable() # Configuring the event loop app = QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) # Running the application _logger.info('Starting version %r; package root: %r', version.__version__, resources.PACKAGE_ROOT) with loop: ctrl = Fuhrer() loop.run_until_complete(ctrl.run()) return 0
def main(): QT_app = QApplication(sys.argv) asyncio_loop = QEventLoop(QT_app) asyncio_loop.set_debug(enabled=True) set_event_loop(asyncio_loop) app = Application(ROUTER) app.settings['debug'] = True app.listen(8015) loop = IOLoop.current() loop.start()
def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.userClient = EchoClientProtocol(self.loop, 'user') self.loop.create_task(self.start()) self.gui = Gui(self.loop, self.userClient) self.loop.run_forever()
def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.client = Client(self.loop, f'user-{int(random()*10000)}') self.loop.create_task(self.start()) self.gui = MyWindow(self.loop, self.client) self.gui.show() self.loop.run_forever()
def main(): # Build default paths for files. dirs = appdirs.AppDirs('QHangups', 'QHangups') default_log_path = os.path.join(dirs.user_data_dir, 'hangups.log') default_cookies_path = os.path.join(dirs.user_data_dir, 'cookies.json') # Setup command line argument parser parser = argparse.ArgumentParser( prog='qhangups', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-d', '--debug', action='store_true', help='log detailed debugging messages') parser.add_argument('--log', default=default_log_path, help='log file path') parser.add_argument('--cookies', default=default_cookies_path, help='cookie storage path') args = parser.parse_args() # Create all necessary directories. for path in [args.log, args.cookies]: directory = os.path.dirname(path) if directory and not os.path.isdir(directory): try: os.makedirs(directory) except OSError as e: sys.exit('Failed to create directory: {}'.format(e)) # Setup logging log_level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(filename=args.log, level=log_level, format=LOG_FORMAT) # asyncio's debugging logs are VERY noisy, so adjust the log level logging.getLogger('asyncio').setLevel(logging.WARNING) # ...and if we don't need Hangups debug logs, then uncomment this: # logging.getLogger('hangups').setLevel(logging.WARNING) # Setup QApplication app = QtGui.QApplication(sys.argv) app.setOrganizationName("QHangups") app.setOrganizationDomain("qhangups.eutopia.cz") app.setApplicationName("QHangups") app.setQuitOnLastWindowClosed(False) app.installTranslator(translator) app.installTranslator(qt_translator) # Start Quamash event loop loop = QEventLoop(app) asyncio.set_event_loop(loop) with loop: widget = QHangupsMainWidget(args.cookies) loop.run_forever()
def __init__(self): QApplication.__init__(self, sys.argv) loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(self.loop) self.userClient = Client(self.loop, args["user"]) self.loop.create_task(self.start()) self.gui = Gui(self.loop, self.userClient) loop.run_forever()
def __init__(self): super().__init__([]) self.setApplicationName('PyPlaybin example') self.setApplicationVersion('1.0.0') self.setOrganizationDomain('net.jeromelaheurte') Playbin.start_glib_loop() self._loop = QEventLoop() asyncio.set_event_loop(self._loop) self.window = MainWindow()
def __init__(self): self.app = QGuiApplication(sys.argv) self.touchscreens = list(filter(lambda d: d.type() == QTouchDevice.TouchScreen, QTouchDevice.devices())) if self.touchscreens: logger.info("touchscreens detected, disabling mouse: %s" % self.touchscreens) # self.app.setOverrideCursor(QCursor(Qt.BlankCursor)) else: logger.error("No touchscreen detected!") self.engine = QQmlApplicationEngine() self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop)
def __init__(self): self.args = args = get_argparser().parse_args() init_logger_from_args(args) if args.log_to_file: log_file = pkg_resources.resource_filename("wand", "log.txt") fh = logging.FileHandler(log_file, mode="wt") fh.setLevel(logger.getEffectiveLevel()) logger.addHandler(fh) logging.getLogger("quamash").addHandler(fh) sys.excepthook = lambda exc_type, exc_value, exc_traceback: \ logger.exception("".join( traceback.format_exception(exc_type, exc_value, exc_traceback))) self.config = load_config(args, "_gui") self.laser_db = {} self.freq_db = {} self.osa_db = {} self.subscribers = {} self.qapp = QtWidgets.QApplication(["WAnD"]) self.loop = QEventLoop(self.qapp) asyncio.set_event_loop(self.loop) atexit.register(self.loop.close) # set program icon icon = QtGui.QIcon() icon.addFile(pkg_resources.resource_filename("wand", "wand.svg")) self.qapp.setWindowIcon(icon) # create main window self.win = MainWindow() self.area = dock.DockArea() self.win.setCentralWidget(self.area) self.win.setWindowTitle("Super-duper Python Wavemeter Viewer!") # populate GUI self.laser_displays = {} for row in self.config["layout"]: prev = None pos = 'bottom' for display_name in row: display = LaserDisplay(display_name, self) self.laser_displays.update({display.laser: display}) self.area.addDock(display.dock, position=pos, relativeTo=prev) pos = 'right' prev = display.dock
def main(): parse_args(sys.argv) q_app = QApplication(sys.argv) q_app.setQuitOnLastWindowClosed(True) q_app.setApplicationName('FeelUOwn') app_event_loop = QEventLoop(q_app) asyncio.set_event_loop(app_event_loop) app = App() app.show() app_event_loop.run_forever() sys.exit(0)
def __init__(self): QApplication.__init__(self, sys.argv) loop = QEventLoop(self) self.loop = loop asyncio.set_event_loop(self.loop) self.gui = LoginDialogControl() self.gui.show() exit_code = self.exec_() if exit_code == 888: self.restart_program() else: sys.exit() loop.run_forever()
def qt_event_loop(): from PyQt5.QtWidgets import QApplication from quamash import QEventLoop app = QApplication([]) loop = QEventLoop(app) asyncio.set_event_loop(loop) return loop
def run(self): with QEventLoop(self.app) as loop: asyncio.set_event_loop(loop) self.window = Window(loop) self.window.setTrigger() self.window.show() loop.run_forever()
def main(): args = get_argparser().parse_args() app = QtWidgets.QApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) file = h5py.File(args.path, "r") try: file["datasets"]["ndscan.axes"][()] except KeyError: QtWidgets.QMessageBox.critical( None, "Not an ndscan file", "No ndscan result datasets found in file: '{}'".format(args.path)) sys.exit(1) try: context = Context() context.set_title(os.path.basename(args.path)) # Old ndscan versions had a rid dataset instead of source_id. datasets = file["datasets"] if "ndscan.source_id" in datasets: context.set_source_id(datasets["ndscan.source_id"][()]) else: context.set_source_id("rid_{}".format(datasets["ndscan.rid"][()])) root = HDF5Root(datasets, context) except Exception as e: QtWidgets.QMessageBox.critical( None, "Error parsing ndscan file", "Error parsing datasets in '{}': {}".format(args.path, e)) sys.exit(2) widget = PlotContainerWidget(root.get_model()) widget.show() sys.exit(app.exec_())
def main(): #QCoreApplication.setAttribute(Qt.AA_UseDesktopOpenGL) #QCoreApplication.setAttribute(Qt.AA_UseOpenGLES) app = MainApplication(sys.argv) loop = QEventLoop(app) asyncio.set_event_loop(loop) app.threadExecutor = QThreadExecutor(10) if app.isClosing(): return 0 #app.setProxyStyle(ProxyStyle()) #return app.exec_() with loop: # context manager calls .close() when loop completes, and releases all resources loop.run_forever()
def test_controller_start(): import sys app = QApplication(sys.argv) app_event_loop = QEventLoop(app) asyncio.set_event_loop(app_event_loop) w = Controller() w.show()
def main(): parser = setup_argparse() args = parser.parse_args() if args.version: print('feeluown {}, fuocore {}'.format(feeluown_version, fuocore_version)) return if is_port_used(23333) or is_port_used(23334): print('\033[0;31m', end='') print( 'Port(23333 or 23334) is used, maybe another feeluown is running?') print('\033[0m', end='') sys.exit(1) debug = args.debug mpv_audio_device = args.mpv_audio_device cli_only = args.no_window logger_config(debug, to_file=args.log_to_file) load_rcfile() player_kwargs = dict(audio_device=bytes(mpv_audio_device, 'utf-8')) # 设置 exception hook sys.excepthook = excepthook if not cli_only: try: import PyQt5 # noqa except ImportError: logger.warning('PyQt5 is not installed,can only use CLI mode.') cli_only = True if not cli_only: from PyQt5.QtWidgets import QApplication from quamash import QEventLoop q_app = QApplication(sys.argv) q_app.setQuitOnLastWindowClosed(True) q_app.setApplicationName('FeelUOwn') app_event_loop = QEventLoop(q_app) asyncio.set_event_loop(app_event_loop) mode = App.CliMode if cli_only else App.GuiMode app = create_app(mode, **player_kwargs) bind_signals(app) event_loop = asyncio.get_event_loop() try: event_loop.run_forever() logger.info('Event loop stopped.') except KeyboardInterrupt: # NOTE: gracefully shutdown? app.shutdown() finally: event_loop.close()
def build(self, init_settings=None): print("\n!! - App::build", os.getpid(), os.getppid()) self.app = QApp(sys.argv) self.app.aboutToQuit.connect(self.kill) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) self.configure(init_settings)
def launch(self): self.app = QApplication([]) self.app.setQuitOnLastWindowClosed(False) self.loop = QEventLoop(self.app) asyncio.set_event_loop(self.loop) signal.signal(signal.SIGINT, signal.SIG_DFL) with self.loop: coro = self.loop.create_server(lambda: CommandReceiver(self), self.address, self.port) server = self.loop.run_until_complete(coro) self.loop.run_forever() server.close() loop.run_until_complete(server.wait_closed())
class App(QApplication): def __init__(self): QApplication.__init__(self, sys.argv) self.loop = QEventLoop(self) asyncio.set_event_loop(self.loop) self.client = Client(self.loop, f'user-{int(random()*10000)}') self.loop.create_task(self.start()) self.gui = MyWindow(self.loop, self.client) self.gui.show() self.loop.run_forever() async def start(self): clientConnection = self.loop.create_connection(lambda: self.client, '127.0.0.1', 8888) await asyncio.wait_for(clientConnection, 10000, loop=self.loop)
def test_controller_start(): import sys app = QApplication(sys.argv) feeluown.config.load() app_event_loop = QEventLoop(app) asyncio.set_event_loop(app_event_loop) w = Glue() w.show()