def run(self): # 这里实在没有找到好的实例代码,将就使用这个来产生错误让faulthandler捕捉到 # 此时这个错误sys.excepthook是无法捕捉到的 # 该异常会弹出python.exe停止运行 a = QCoreApplication(sys.argv) p = QPixmap(QSize(10, 10)) a.exec_()
def __init__(self, timeout=2000, size=2**28): self.app = QCoreApplication.instance() if self.app is None: self.app = QCoreApplication([]) self.sock = QLocalSocket() self.sock.connectToServer("LivePlot") if not self.sock.waitForConnected(): raise EnvironmentError("Couldn't find LivePlotter instance") self.sock.disconnected.connect(self.disconnect_received) key = str(uuid.uuid4()) self.shared_mem = QSharedMemory(key) if not self.shared_mem.create(size): raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString()) logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size())) self.sock.write(key.encode()) self.sock.waitForBytesWritten() self.is_connected = True self.timeout = timeout atexit.register(self.close)
def init_country_names_from_code(locale): '''Init the country description as found in GCompris geography/resource/board/board*.qml''' '''in the global descriptions hash''' po = None try: po = polib.pofile(gcompris_qt + '/po/gcompris_' + locale + '.po') except: print("**ERROR: Failed to load po file %s**" % ('/po/gcompris_' + locale + '.po')) print('') app = QCoreApplication(sys.argv) engine = QQmlEngine() component = QQmlComponent(engine) for qml in glob.glob(gcompris_qt + '/src/activities/geography/resource/board/*.qml'): component.loadUrl(QUrl(qml)) board = component.create() levels = board.property('levels') for level in levels.toVariant(): if 'soundFile' in level and 'toolTipText' in level: sound = level['soundFile'].split('/')[-1].replace('$CA', 'ogg') tooltip = level['toolTipText'] if po: tooltip = po.find(tooltip).msgstr if po.find( tooltip) else tooltip descriptions[sound] = tooltip
def setQApplication(self): self.app = QCoreApplication(sys.argv) self.app.setOrganizationName(self.name) self.app.setOrganizationDomain(self.name) self.app.setApplicationName(self.name) self.translator = QTranslator() self.settings = QSettings()
def main() -> None: signal.signal(signal.SIGINT, signal.SIG_DFL) app = QCoreApplication([]) testo = Testo() # This is causing the problem def a() -> None: # Using 'app' in a local function seems to be what requires # the manual 'del app' call, otherwise the garbage collector # needs to do the cleanup and probably comes to late, as # another QCoreApplication instance might have already been # created. print(app) # As long as the function isn't using 'app' everything seems to be # ok. def b() -> None: print("nothing") # If 'b' is used instead of 'a' the problem goes away testo.sig_test.connect(a) QTimer.singleShot(1000, app.quit) print("exec") app.exec() print("exec:done")
def start(args): app = QCoreApplication(sys.argv) sys.excepthook = traceback.print_exception server = DedicatedServer(args.level) server.SNAPSHOT_INTERVAL = args.interval server.start(args.host, args.port, args.ssl) # Allow the use of Ctrl-C to stop the server def sigint_handler(_, __): server.stop() app.exit(0) signal.signal(signal.SIGINT, sigint_handler) # This timer gives the application a chance to be interrupted every 50 ms # even if it stuck in a loop or something def safe_timer(timeout, func, *args, **kwargs): def timer_event(): try: func(*args, **kwargs) finally: QTimer.singleShot(timeout, timer_event) QTimer.singleShot(timeout, timer_event) safe_timer(50, lambda: None) return app.exec_()
def main(): import sys app = QCoreApplication(sys.argv) # noqa: F841 if not QDBusConnection.sessionBus().isConnected(): sys.stderr.write("Cannot connect to the D-Bus session bus.\n" "To start it, run:\n" "\teval `dbus-launch --auto-syntax`\n") sys.exit(1) iface = QDBusInterface(SERVICE_NAME, "/", "", QDBusConnection.sessionBus()) if iface.isValid(): msg = iface.call("ping", sys.argv[1] if len(sys.argv) > 1 else "") reply = QDBusReply(msg) if reply.isValid(): sys.stdout.write("Reply was: %s\n" % reply.value()) sys.exit() sys.stderr.write("Call failed: %s\n" % reply.error().message()) sys.exit(1) sys.stderr.write("%s\n" % QDBusConnection.sessionBus().lastError().message()) sys.exit(1)
def createApp(self, appName): if LINUX: # AA_X11InitThreads is not available on old PyQt versions try: attr = Qt.AA_X11InitThreads except: attr = 10 QApplication.setAttribute(attr) if MACOS: QApplication.setAttribute(Qt.AA_DontShowIconsInMenus) self.fApp = QCoreApplication( sys.argv) if gCarla.nogui else QApplication(sys.argv) self.fApp.setApplicationName(appName) self.fApp.setApplicationVersion(VERSION) self.fApp.setOrganizationName("falkTX") if gCarla.nogui: return if appName.lower() == "carla-control": self.fApp.setWindowIcon(QIcon(":/scalable/carla-control.svg")) else: self.fApp.setWindowIcon(QIcon(":/scalable/carla.svg")) print("Using \"%s\" theme" % self.fApp.style().objectName())
def main(args): """ The entry point of a Python program. """ app = QCoreApplication(sys.argv) sys.excepthook = traceback.print_exception server = DedicatedServer(args.ssl) server.start(args.host, args.port) # Allow the use of Ctrl-C to stop the server def sigint_handler(signum, frame): server.stop() app.exit(0) signal.signal(signal.SIGINT, sigint_handler) def safe_timer(timeout, func, *args, **kwargs): def timer_event(): try: func(*args, **kwargs) finally: QTimer.singleShot(timeout, timer_event) QTimer.singleShot(timeout, timer_event) safe_timer(50, lambda: None) return app.exec_()
def createApp(self, appName): if LINUX: # AA_X11InitThreads is not available on old PyQt versions try: attr = Qt.AA_X11InitThreads except: attr = 10 QApplication.setAttribute(attr) if MACOS: QApplication.setAttribute(Qt.AA_DontShowIconsInMenus) args = sys.argv[:] if WINDOWS: args += ["-platform", "windows:fontengine=freetype"] self.fApp = QCoreApplication(args) if gCarla.nogui else QApplication(args) self.fApp.setApplicationName(appName) self.fApp.setApplicationVersion(VERSION) self.fApp.setOrganizationName("falkTX") if gCarla.nogui: return if appName.lower() == "carla-control": self.fApp.setWindowIcon(QIcon(":/scalable/carla-control.svg")) else: self.fApp.setWindowIcon(QIcon(":/scalable/carla.svg"))
def main(): import sys app = QCoreApplication(sys.argv) f = QFile() f.open(sys.stdout.fileno(), QIODevice.WriteOnly) out = QTextStream(f) serialPortInfos = QSerialPortInfo.availablePorts() out << "Total number of ports available: " << len(serialPortInfos) << "\n" blankString = "N/A" description = "" manufacturer = "" serialNumber = "" for serialPortInfo in serialPortInfos: description = serialPortInfo.description() manufacturer = serialPortInfo.manufacturer() serialNumber = serialPortInfo.serialNumber() out << "\nPort: " << serialPortInfo.portName( ) << "\nLocation: " << serialPortInfo.systemLocation( ) << "\nDescription: " << ( description if description else blankString) << "\nManufacturer: " << ( manufacturer if manufacturer else blankString ) << "\nSerial number: " << ( serialNumber if serialNumber else blankString ) << "\nVendor Identifier: " << ( QByteArray.number(serialPortInfo.vendorIdentifier(), 16) if serialPortInfo.hasVendorIdentifier() else blankString ) << "\nProduct Identifier: " << ( QByteArray.number(serialPortInfo.productIdentifier(), 16) if serialPortInfo.hasProductIdentifier() else blankString) << "\n"
def main(): # TODO: find a cleaner way of shutting down signal.signal(signal.SIGINT, signal.SIG_DFL) config = load_config() debounce_sec = config['debounce'] display_name = config['display_name'] script_working_dir = config['_script_working_dir'] dbus_interface_name = config['_dbus']['interface_name'] dbus_path = config['_dbus']['path'] dbus_signal_name = config['_dbus']['signal_name'] connect_scripts = config['on_connect'] disconnect_scripts = config['on_disconnect'] app = QCoreApplication(sys.argv) loop = DBusQtMainLoop(set_as_default=True) bus = dbus.SessionBus() signal_runner = SignalRunner(debounce_sec, display_name, cwd=script_working_dir) for script in connect_scripts: signal_runner.add_connect_script(script) for script in disconnect_scripts: signal_runner.add_disconnect_script(script) bus.add_signal_receiver(handler_function=signal_runner.run, dbus_interface=dbus_interface_name, path=dbus_path, signal_name=dbus_signal_name) sys.exit(app.exec_())
def init_app(argv=None, gui=True): """ Initialize qt runtime, deal with common issues (such as installing an exception handler), and return a ``QApplication`` object. If ``gui`` is false, return a ``QCoreApplication`` instead. """ warnings.filterwarnings( "default", module='(madgui|cpymad|minrpc|pydicti).*') set_app_id('hit.madgui') init_stdio() # QApplication needs a valid argument list: if argv is None: argv = sys.argv if gui: from PyQt5.QtWidgets import QApplication from madgui.util.qt import load_icon_resource from importlib_resources import read_text app = QApplication(argv) app.setWindowIcon(load_icon_resource('madgui.data', 'icon.xpm')) app.setStyleSheet(read_text('madgui.data', 'style.css')) # matplotlib must be imported *after* Qt; # must be selected before importing matplotlib.backends: import matplotlib matplotlib.use('Qt5Agg') else: app = QCoreApplication(argv) app.setApplicationName('madgui') app.setApplicationVersion(__version__) app.setOrganizationName('HIT Betriebs GmbH') app.setOrganizationDomain('https://www.klinikum.uni-heidelberg.de/hit') # Print uncaught exceptions. This changes the default behaviour on PyQt5, # where an uncaught exception would usually cause the program to abort. sys.excepthook = traceback.print_exception setup_interrupt_handling(app) return app
def using_q_runnable(): app = QCoreApplication([]) # create a runnable object from Runnable class, which is subclassing from QRunnable runnable = Runnable() # then use QThreadPool to mgmt runnable object QThreadPool.globalInstance().start(runnable) sys.exit(app.exec_())
def main(): signal.signal(signal.SIGINT, signal.SIG_DFL) app = QCoreApplication([]) bus = QDBusConnection.systemBus() udisk_manager = UDiskManager(bus) udisk_manager.print_info() app.exec()
def using_q_thread(): app = QCoreApplication([]) thread = MainApp() th = QThread() thread.finished.connect(app.exit) thread.moveToThread(th) thread.start() sys.exit(app.exec_())
def run(): app = QCoreApplication(sys.argv) ex = MainWorker(app) ex.start(sys.argv) app.exec_()
def init(self): if self.app is None: self.app = QCoreApplication(sys.argv) set_app_data(self.app) if self.data is None: self.data = DataObject() dataPath = get_user_data_path() self.data.load(dataPath)
def test_qt_count_up(): app = QCoreApplication([]) def count_up(count): for _ in range(count): yield 1 gen_timer(app, count_up(3), done=app.quit) app.exec_()
def __init__(self): Mem.__init__(self) self.app = QCoreApplication(argv) self.app.setOrganizationName("caloriestracker") self.app.setOrganizationDomain("caloriestracker") self.app.setApplicationName("caloriestracker") self.settings = QSettings() self.localzone = self.settings.value("mem/localzone", "Europe/Madrid") self.load_translation() self.create_parser()
def setup_app(database_filename, argv): create_initial_directories() ext.App = QCoreApplication(argv) tools.prepare_log(ext.LogFilepath) CDatabaseManager(database_filename) ext.logger.info('Started')
def start_window_manager(): app = QCoreApplication(sys.argv) bluetooth_speaker = BluethoothSpeaker() qt_thread = QtThread(app) qt_thread.connect_bluetooth_speaker.connect(bluetooth_speaker.connect) qt_thread.start() sys.exit(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 main(): #app = GitterApp(sys.argv) app = QCoreApplication(sys.argv) loop = DBusQtMainLoop(set_as_default=True) bus = dbus.SessionBus() QTimer().singleShot(0, test_cm) QTimer().singleShot(5000, app.quit) app.exec_()
def main(): app = QCoreApplication(sys.argv) server = Server() server.start() print('Server Running...') timer = QTimer() timer.start(500) timer.timeout.connect(lambda: None) sys.exit(app.exec_())
def live_generate(opt, model=None): import signal from PyQt5.QtCore import QFileSystemWatcher from PyQt5.QtCore import QCoreApplication, QTimer app = QCoreApplication([]) out_dir = opt.output shape = (opt.loadSize, opt.loadSize) opt.nThreads = 1 # test code only supports nThreads = 1 opt.batchSize = 1 # test code only supports batchSize = 1 opt.serial_batches = True # no shuffle opt.no_flip = True # no flip opt.label_nc = 0 opt.no_instance = True opt.replace = True model = create_model(opt) def on_file_changed(path): print(f"file {path} changed") if path not in watcher.files(): if os.path.exists(path): print("new file(s). adding to watch") if os.path.isdir(path): paths = get_images(path) else: paths = [path] watcher.addPaths(paths) opt.image = path do_generate(opt, model) imgs = [] if os.path.isdir(opt.image): imgs = get_images(opt.image) watcher = QFileSystemWatcher([opt.image, *imgs]) watcher.directoryChanged.connect(on_file_changed) watcher.fileChanged.connect(on_file_changed) timer = QTimer() timer.start(500) # You may change this if you wish. timer.timeout.connect(lambda: None) # Let the interpreter run each 500 ms. def sigint_handler(*args): QCoreApplication.quit() signal.signal(signal.SIGTERM, sigint_handler) app.exec_()
def main(args): """ The entry point of a Python program. """ # Allow the use of Ctrl-C to stop the server signal.signal(signal.SIGINT, signal.SIG_DFL) app = QCoreApplication(sys.argv) server = DedicatedServer() server.start(args.host, args.port) return app.exec_()
def app(): """Fixture required to be able to process events and quit smoothly the application.""" from PyQt5.QtCore import QCoreApplication, QTimer app = QCoreApplication([]) # Little trick here! See Application.__init__() for details. timer = QTimer() timer.timeout.connect(lambda: None) timer.start(100) yield app
def main(argv: List[str]) -> None: signal.signal(signal.SIGINT, signal.SIG_DFL) app = QCoreApplication([]) # noqa: F841 mime_db = QMimeDatabase() mt = mime_db.mimeTypeForName("application/x-rar") print("name:", mt.name()) print("iconName:", mt.iconName()) print("genericIconName:", mt.genericIconName()) print("aliases:", ", ".join(mt.aliases())) sys.exit(0)
def testscaleLabel(): qapp = QCoreApplication(sys.argv) try: layout = listdir("E:\\WorkSpace\\PPL\\data\\LSUN\\layout\\layout_seg", ".mat") except: layout = listdir("/data4T1/samhu/LSUN/layout/layout_seg", ".mat") lmat = loadmat(layout[135])['layout'].copy() img = convertLabelToQImage(lmat) img.save('./lbl.png') lmatscaled = scaleLabel(lmat, 512) imgscaled = convertLabelToQImage(lmatscaled) imgscaled.save('./scalelbl.png')