def monitor(): try: from apscheduler.schedulers.qt import QtScheduler from apscheduler.triggers.cron import CronTrigger app = QCoreApplication(sys.argv) global me me = Monitor(cf) sched = QtScheduler() schedtime = [y.split(':') for x in cf.get('monitor', 'schedtime').strip().split('|') for y in x.split(',')] trigger_start = CronTrigger(day_of_week=schedtime[0][0], hour=int(schedtime[1][0]), minute=int(schedtime[1][1])) logger.info('schedulers:start dayofweek:%s startime:%s ', schedtime[0][0], schedtime[1]) trigger_stop = CronTrigger(day_of_week=schedtime[2][0], hour=int(schedtime[3][0]), minute=int(schedtime[3][1])) logger.info('schedulers:stop dayofweek:%s stoptime:%s', schedtime[2][0], schedtime[3]) sched.add_job(start, trigger_start, misfire_grace_time = 10) sched.add_job(stop, trigger_stop, misfire_grace_time = 10) sched.start() working_time_range = parse_work_time(cf.get("monitor", "workingtime")) #上面的任务调度只有在未来时间才会触发 #这里加上判断当前时间如果在工作时间(时间段和交易日都要符合),则要开启 if is_trade_day(cf) and is_working_time(working_time_range): start() app.exec_() except BaseException,e: logger.exception(e)
def start(): app = QCoreApplication([]) bus = QDBusConnection.sessionBus() server = MyServer() bus.registerObject('/org/mpris/MediaPlayer2', server) bus.registerService('org.mpris.MediaPlayer2.grooveshark') app.exec_()
def main(): # Creates a QCoreApplication object. app = QCoreApplication(sys.argv) server = Server() print "Process ID: %i" % app.applicationPid() # Run application. app.exec_()
def monitor(): try: from apscheduler.schedulers.qt import QtScheduler app = QCoreApplication(sys.argv) global me me = Monitor(cf) sched = QtScheduler() # m = Main() # sched.add_job(start, 'cron', id='first', day_of_week ='0-4', hour = 9, minute = 11) # sched.add_job(stop, 'cron', id='second', day_of_week ='0-4', hour = 15, minute = 20) # sched.add_job(start, 'cron', id='first', hour = 9, minute = 16) # sched.add_job(stop, 'cron', id='second', hour = 15, minute = 10) #如有显式配置调度时间,则根据调度时间来设置调度计划 #如果没有配置,则分别取工作时间的最前和最后时间作为任务计划的开始和结束时间 if cf.has_option('monitor','schedtime'): schedtime = cf.get('monitor', 'schedtime').strip().split('~') startime = schedtime[0].split(':') stoptime = schedtime[1].split(':') else: workingtimelist = [] for x in cf.get('monitor', 'workingtime').strip().split(','): for x1 in x.split('~'): workingtimelist.append(x1) #workingtimelist.sort() startime = workingtimelist[0].split(':') stoptime = workingtimelist[-1].split(':') sched.add_job(start, 'cron', id='first', day_of_week='0-4', hour=int(startime[0]), minute=int(startime[1])) sched.add_job(stop, 'cron', id='second', day_of_week='0-4', hour=int(stoptime[0]), minute=int(stoptime[1])) logger.info('schedulers startime:%s stoptime:%s', startime, stoptime) sched.start() #上面的任务调度只有在未来时间才会触发 #这里加上判断当前时间如果在工作时间,则要开启 worktime = cf.get("monitor", "workingtime").split(',') worktimerange = [] for i in range(len(worktime)): worktimerange.append(worktime[i].split('~')) time_now = datetime.now().strftime("%H:%M") for i in range(len(worktimerange)): if time_now > worktimerange[i][0] and time_now < worktimerange[i][1]: logger.info('now:%s is in the worktimerange,will start the job immediately', time_now) start() app.exec_() except BaseException,e: logger.exception(e)
def testZmqRequestReply(): app = QCoreApplication([]) server = ZmqRequestReplyThread(port=7000) # def received(origin, timeStamp, request): # age = time.time()-timeStamp # print("Received from", origin, "time stamp=", timeStamp, "age=", age, "s", "Request=", request # server.requestReceived.connect(received) timer = QTimer() timer.singleShot(1000, server.start) timer.singleShot(20000, server.stop) app.exec_()
def test(): """测试函数""" from datetime import datetime from PyQt4.QtCore import QCoreApplication def simpletest(event): print(u'处理每秒触发的计时器事件:%s' % str(datetime.now())) app = QCoreApplication('VnTrader') ee = EventEngine2() ee.register(EVENT_TIMER, simpletest) ee.start() app.exec_()
def test(): try: from apscheduler.schedulers.qt import QtScheduler app = QCoreApplication(sys.argv) global me me = Monitor(cf) sched = QtScheduler() # m = Main() # sched.add_job(start, 'cron', id='first', day_of_week ='0-4', hour = 9, minute = 11) # sched.add_job(stop, 'cron', id='second', day_of_week ='0-4', hour = 15, minute = 20) sched.add_job(start, 'cron', id='first', hour = 17, minute = 21,second = 0) sched.add_job(stop, 'cron', id='second', hour = 21, minute = 10) sched.start() app.exec_() except BaseException,e: logger.exception(e)
def testZmqSubscriber(): port = 5556 app = QCoreApplication([]) sub = ZmqSubscriber(port) def received(origin, item, value, timeStamp): age = time.time() - timeStamp print("Received from", origin, "item=", item, "value=", value, "time stamp=", timeStamp, "age=", age, "s") sub.floatReceived.connect(received) timer = QTimer() timer.singleShot(1000, sub.start) timer.singleShot(20000, sub.stop) app.exec_()
def main(): signal.signal(signal.SIGINT, sigint_handler) app = QCoreApplication(sys.argv) ex = GUIServer() sys.exit(app.exec_())
def test(): """测试函数""" import sys from datetime import datetime from PyQt4.QtCore import QCoreApplication def simpletest(event): print u'处理每秒触发的计时器事件:%s' % str(datetime.now()) app = QCoreApplication(sys.argv) ee = EventEngine() ee.register(EVENT_TIMER, simpletest) ee.start() app.exec_()
class GateTest(QObject): def setUp(self): self.app = QCoreApplication(sys.argv) self._occurrences = Counter() def _increment(self, _, __): self._occurrences[self.sender()] += 1 for limit in self._limit: if self._occurrences == limit: self.app.quit() break def _wait(self): self._limit = [Counter(l) for l in self._limit] if self._limit[0]: self.app.exec_()
def main(argv): """The main function for the tunnel server.""" fix_turkish_locale() if not check_proxy_enabled(*argv[1:]): sys.stdout.write("Proxy not enabled.") sys.stdout.flush() else: if sys.platform.startswith("linux"): install_qt_dbus() app = QCoreApplication(argv) cookie = str(uuid.uuid4()) tunnel_server = TunnelServer(cookie) sys.stdout.write("%s: %d\n" % (TUNNEL_PORT_LABEL, tunnel_server.port) + "%s: %s\n" % (TUNNEL_COOKIE_LABEL, cookie)) sys.stdout.flush() app.exec_()
def runow(): try: app = QCoreApplication(sys.argv) me = Monitor(cf) me.start() sys.exit(app.exec_()) except BaseException, e: logger.exception(e)
def test(): """测试函数""" import sys from datetime import datetime from PyQt4.QtCore import QCoreApplication def simpletest(event): print('处理每秒触发的计时器事件:%s' % str(datetime.now())) app = QCoreApplication(sys.argv) ee = EventEngine2() #ee.register(EVENT_TIMER, simpletest) ee.registerGeneralHandler(simpletest) ee.start() app.exec_()
def test(): """测试函数""" """test function""" import sys from datetime import datetime from PyQt4.QtCore import QCoreApplication def simpletest(event): print u'处理每秒触发的计时器事件:%s' % str(datetime.now()) def simpletest2(event): print "this is additional test: %s" % str(datetime.now()) app = QCoreApplication(sys.argv) ee = EventEngine2() ee.register(EVENT_TIMER, simpletest) ee.register(EVENT_TIMER, simpletest2) ee.start() app.exec_()
def test_engine1(): import sys from PyQt4.QtCore import QCoreApplication app = QCoreApplication(sys.argv) ee = EventEngine() ee.register(EVENT_TIMER, simple_test) ee.start() sys.exit(app.exec_())
def main(): app = QCoreApplication(sys.argv) mainEngine = MainEngine() # 若需要连接数据库,则启动 mainEngine.dbConnect() # 指定的连接配置 mainEngine.connect('CTP_Prod') # 加载cta的配置 mainEngine.ctaEngine.loadSetting() # 初始化策略,如果多个,则需要逐一初始化多个 mainEngine.ctaEngine.initStrategy(u'S26_PTA套利') # 逐一启动策略 mainEngine.ctaEngine.startStrategy(u'S26_PTA套利') logM = LogMonitor(mainEngine.eventEngine) errorM = ErrorMonitor(mainEngine.eventEngine) tradeM = TradeMonitor(mainEngine.eventEngine) orderM = OrderMonitor(mainEngine.eventEngine, mainEngine) positionM = PositionMonitor(mainEngine.eventEngine) accountM = AccountMonitor(mainEngine.eventEngine) app.exec_()
def main(): try: from auto.mainengine import Monitor from auto.mainengine import Business from PyQt4.QtCore import QCoreApplication """主程序入口""" app = QCoreApplication(sys.argv) logging.config.fileConfig(os.path.join(os.getcwd(), baseconfdir, loggingconf)) logger = logging.getLogger("run") cf = ConfigParser.ConfigParser() cf.read(os.path.join(os.getcwd(), baseconfdir, businessconf)) me = Business(cf) sys.exit(app.exec_()) except BaseException,e: logger.exception(e)
def main(): try: from auto.mainengine import Monitor from auto.mainengine import Business from PyQt4.QtCore import QCoreApplication """主程序入口""" app = QCoreApplication(sys.argv) logging.config.fileConfig( os.path.join(os.getcwd(), baseconfdir, loggingconf)) logger = logging.getLogger("run") cf = ConfigParser.ConfigParser() cf.read(os.path.join(os.getcwd(), baseconfdir, businessconf)) me = Business(cf) sys.exit(app.exec_()) except BaseException, e: logger.exception(e)
class Qt4Reactor(QObject, PosixReactorBase): implements(IReactorFDSet) # Note: @pyqtSignature is necessary for QMetaObject.invokeMethod() to work. # @pyqtSlot is not used for compatibility with PyQt versions before 4.5. # Note: Twisted 10.0 and earlier is unable to wake up Qt event loop on SIGCHLD. # This does not pose a problem for GUI apps and was fixed in Twisted 10.1 so no workaround here. def __init__(self): QObject.__init__(self) self._readers = {} self._writers = {} self._timer = QTimer() self._timer.setSingleShot(True) self.connect(self._timer, SIGNAL("timeout()"), self._timerSlot) self._eventLoop = QCoreApplication.instance() if self._eventLoop is None: # create dummy application for testing self._eventLoop = QCoreApplication([]) PosixReactorBase.__init__(self) # goes last, because it calls addReader def _scheduleSimulation(self, timeout=0): if timeout is None: self._timer.stop() else: self._timer.start(timeout * 1000) @pyqtSignature("") def _timerSlot(self): self.runUntilCurrent() self._scheduleSimulation(self.timeout()) def _addNotifier(self, descriptor, descmap, type): if descriptor not in descmap: fd = descriptor.fileno() if fd == -1: raise RuntimeError("Invalid file descriptor") notifier = QSocketNotifier(fd, type) descmap[descriptor] = notifier notifier._descriptor = descriptor self.connect(notifier, SIGNAL("activated(int)"), self._notifierSlot) notifier.setEnabled(True) def _removeNotifier(self, descriptor, descmap): notifier = descmap.pop(descriptor, None) if notifier is not None: notifier.setEnabled(False) self.disconnect(notifier, SIGNAL("activated(int)"), self._notifierSlot) notifier._descriptor = None notifier.deleteLater() @pyqtSignature("") def _notifierSlot(self): # Note: in some tests on Ubuntu 10.4 (PyQt 4.7.2) new-style signal connections result # in NULL QObject.sender() here. Old style signal connections do not have this problem. notifier = self.sender() notifier.setEnabled(False) descriptor = notifier._descriptor if descriptor is None: return isRead = (notifier.type() == notifier.Read) try: if isRead: why = descriptor.doRead() else: why = descriptor.doWrite() except: log.err() why = sys.exc_info()[1] if descriptor.fileno() != notifier.socket(): why = ConnectionFdescWentAway('Filedescriptor went away') if why: self._disconnectSelectable(descriptor, why, isRead) elif notifier._descriptor: # check if not disconnected in doRead/doWrite notifier.setEnabled(True) # Twisted (FTP) expects due timed events to be delivered after each IO event, # so that invoking callLater(0, fn) from IO callback results in fn() being called before # the next IO callback. self.runUntilCurrent() def addReader(self, reader): self._addNotifier(reader, self._readers, QSocketNotifier.Read) def addWriter(self, writer): self._addNotifier(writer, self._writers, QSocketNotifier.Write) def removeReader(self, reader): self._removeNotifier(reader, self._readers) def removeWriter(self, writer): self._removeNotifier(writer, self._writers) def removeAll(self): return self._removeAll(self._readers, self._writers) def getReaders(self): return self._readers.keys() def getWriters(self): return self._writers.keys() def callLater(self, *args, **kwargs): result = PosixReactorBase.callLater(self, *args, **kwargs) self._scheduleSimulation() return result def _moveCallLaterSooner(self, tple): result = PosixReactorBase._moveCallLaterSooner(self, tple) self._scheduleSimulate() return result def doIteration(self, delay): # Note: some tests fail on Ubuntu 10.4 when processEvents is called with zero delay. # Setting the minimal delay to something > 0 or or calling processEvents() twice # fixes the problem. self._eventLoop.processEvents(QEventLoop.AllEvents, max(1, delay) * 1000) def mainLoop(self): self._eventLoop.exec_() def stop(self): PosixReactorBase.stop(self) self._scheduleSimulation() def crash(self): PosixReactorBase.crash(self) self._eventLoop.quit() if sys.platform == "win32": # On Windows, we can wake up by simply posting a message to the main loop. # Other systems call wakeUp() from unix signal handlers (which are forbidden from making # any Qt calls) and have to use the default pipe based waker. def installWaker(self): pass def wakeUp(self): QMetaObject.invokeMethod(self, "_timerSlot", Qt.QueuedConnection)
class Qt4Reactor(QObject, PosixReactorBase): implements(IReactorFDSet) # Note: @pyqtSignature is necessary for QMetaObject.invokeMethod() to work. # @pyqtSlot is not used for compatibility with PyQt versions before 4.5. # Note: Twisted 10.0 and earlier is unable to wake up Qt event loop on SIGCHLD. # This does not pose a problem for GUI apps and was fixed in Twisted 10.1 so no workaround here. def __init__(self): QObject.__init__(self) self._readers = {} self._writers = {} self._timer = QTimer() self._timer.setSingleShot(True) self.connect(self._timer, SIGNAL("timeout()"), self._timerSlot) self._eventLoop = QCoreApplication.instance() if self._eventLoop is None: # create dummy application for testing self._eventLoop = QCoreApplication([]) PosixReactorBase.__init__(self) # goes last, because it calls addReader def _scheduleSimulation(self, timeout=0): if timeout is None: self._timer.stop() else: self._timer.start(timeout * 1000) @pyqtSignature("") def _timerSlot(self): self.runUntilCurrent() self._scheduleSimulation(self.timeout()) def _addNotifier(self, descriptor, descmap, type): if descriptor not in descmap: fd = descriptor.fileno() if fd == -1: raise RuntimeError("Invalid file descriptor") notifier = QSocketNotifier(fd, type) descmap[descriptor] = notifier notifier._descriptor = descriptor self.connect(notifier, SIGNAL("activated(int)"), self._notifierSlot) notifier.setEnabled(True) def _removeNotifier(self, descriptor, descmap): notifier = descmap.pop(descriptor, None) if notifier is not None: notifier.setEnabled(False) self.disconnect(notifier, SIGNAL("activated(int)"), self._notifierSlot) notifier._descriptor = None notifier.deleteLater() @pyqtSignature("") def _notifierSlot(self): # Note: in some tests on Ubuntu 10.4 (PyQt 4.7.2) new-style signal connections result # in NULL QObject.sender() here. Old style signal connections do not have this problem. notifier = self.sender() notifier.setEnabled(False) descriptor = notifier._descriptor if descriptor is None: return isRead = notifier.type() == notifier.Read try: if isRead: why = descriptor.doRead() else: why = descriptor.doWrite() except: log.err() why = sys.exc_info()[1] if descriptor.fileno() != notifier.socket(): why = ConnectionFdescWentAway("Filedescriptor went away") if why: self._disconnectSelectable(descriptor, why, isRead) elif notifier._descriptor: # check if not disconnected in doRead/doWrite notifier.setEnabled(True) # Twisted (FTP) expects due timed events to be delivered after each IO event, # so that invoking callLater(0, fn) from IO callback results in fn() being called before # the next IO callback. self.runUntilCurrent() def addReader(self, reader): self._addNotifier(reader, self._readers, QSocketNotifier.Read) def addWriter(self, writer): self._addNotifier(writer, self._writers, QSocketNotifier.Write) def removeReader(self, reader): self._removeNotifier(reader, self._readers) def removeWriter(self, writer): self._removeNotifier(writer, self._writers) def removeAll(self): return self._removeAll(self._readers, self._writers) def getReaders(self): return self._readers.keys() def getWriters(self): return self._writers.keys() def callLater(self, *args, **kwargs): result = PosixReactorBase.callLater(self, *args, **kwargs) self._scheduleSimulation() return result def _moveCallLaterSooner(self, tple): result = PosixReactorBase._moveCallLaterSooner(self, tple) self._scheduleSimulate() return result def doIteration(self, delay): # Note: some tests fail on Ubuntu 10.4 when processEvents is called with zero delay. # Setting the minimal delay to something > 0 or or calling processEvents() twice # fixes the problem. self._eventLoop.processEvents(QEventLoop.AllEvents, max(1, delay) * 1000) def mainLoop(self): self._eventLoop.exec_() def stop(self): PosixReactorBase.stop(self) self._scheduleSimulation() def crash(self): PosixReactorBase.crash(self) self._eventLoop.quit() if sys.platform == "win32": # On Windows, we can wake up by simply posting a message to the main loop. # Other systems call wakeUp() from unix signal handlers (which are forbidden from making # any Qt calls) and have to use the default pipe based waker. def installWaker(self): pass def wakeUp(self): QMetaObject.invokeMethod(self, "_timerSlot", Qt.QueuedConnection)
control_server = ControlServer() app.aboutToQuit.connect(control_server.disconnect) QTimer.singleShot(0, control_server.start) proxies = [None] * 4 for i in range(4): proxy = ProxyServer(dl_num=i + 1) if i > 0: proxies[i - 1].reception_finished.connect(proxy.begin_acquiring) QTimer.singleShot(0, proxy.start) app.aboutToQuit.connect(proxy.disconnect) proxies[i] = proxy control_server.start_received.connect(proxies[0].begin_acquiring) # EXIT METHOD # OPTION 1: wait for 'quit' command to exit when all finished #proxies[3].reception_finished.connect(control_server.last_finished) #control_server.quit_app.connect(app.quit) # OPTION 2: exit automatically when all finished proxies[3].reception_finished.connect(app.quit) # END EXIT METHOD # run! log.info('starting event loop...') r = app.exec_() log.info('exiting event loop...') sys.exit(r)
def stop(self): if(self._t is not None): print 'Stopping thread...' self._t.cancel() self._t = None GPIO.output(self.HEAT, False) GPIO.output(self.COOL, False) GPIO.output(self.FAN, False) if __name__ == "__main__": from PyQt4.QtCore import QCoreApplication import sys, pdb app = QCoreApplication(sys.argv) # Testing the thermostat on the console t = Thermostat(parent=app, test=True) t.start() def uncaught(type, value, traceback): print type, value, traceback QCoreApplication.quit() sys.excepthook = uncaught app.exec_() print 'Stopping...' t.stop()
print "New connection..." _s = self.nextPendingConnection() _s.readyRead.connect(self.read) self._sockets.append(_s) def read(self): _s = self.sender() msg = _s.readLine().data() if not msg.endswith(";"): print "Message not correctly terminated." return else: msg = msg[:-1] data = msg.split(":") method = data[0] if method in message.messages: getattr(self, method)(*data[1:]) else: print "Missing method: %s" % method @message def cmd(self, *args): print "Command: %s" % ",".join([arg for arg in args]) if __name__ == "__main__": if len(argv) < 3: print "Usage: python client.py <HOST> <PORT>" exit() a = QCoreApplication(argv) s = Server() a.exec_()
class mcu: '''Main MCU (or "ingester") class. Upon initialization, the MCU loads a config file describing all the devices to connect to, along with the drivers for the devices and settings for the drivers. The MCU publishes all data read in by the drivers on the bus for other programs to use, and accepts calls over the bus to publish data back to the drivers for delivery over the wire.''' app = None config = None devices = None class dbus_signaller(dbus.service.Object): def __init(self, conn, object_path): dbus.service.Object.__init__(self, conn, object_path) # note that although the object_path encodes the real # device generating the data, it can occasionally be # useful to let the driver specify the "real" # originating device. for example, the playback # driver sends along the original generator of a # sentence when it plays back log data. that is why # we have a device argument to this method. @dbus.service.signal('org.boatlogger.MCU', signature='ss') def publish_sentence(self, device, data): print 'publishing: '+repr(data)+' from '+device # pass class device: name = None config = None module = None driver = None publisher = None io_handlers = None def __init__(self, mcu, name, config): self.name = name self.config = config self.module = __import__(config['driver']) self.publisher = mcu.dbus_signaller(mcu.dbus, '/org/boatlogger/devices/'+name) self.driver = self.module.driver(name, config, self.publisher) self.make_io_handlers(mcu) def make_io_handlers(self, mcu): fd = self.driver.get_fd() self.io_handlers = [(QSocketNotifier(fd, QSocketNotifier.Read), (lambda fd: self.driver.read(fd))), (QSocketNotifier(fd, QSocketNotifier.Write), (lambda fd: self.driver.write(fd)))] # (QSocketNotifier(fd, QSocketNotifier.Write), # self.make_error_handler(self.name))] for notifier, callback in self.io_handlers: mcu.app.connect(notifier, SIGNAL('activated(int)'), callback) def make_error_handler(self, name): def error_handler(fd): raise DriverException('I/O error in '+name) return error_handler def __init__(self, config='mcu.ini'): self.app = QCoreApplication(sys.argv) dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True) self.dbus = dbus.SystemBus() # load config file print('loading '+config) self.config = configobj.ConfigObj(config, file_error=True, unrepr=True) print repr(self.config) # initialize i/o drivers and callbacks for p in ['utility_path','path']: sys.path.append(self.config['drivers'][p]) self.devices = [self.device(self, name, self.config[name]) for name in self.config['devices']] def run(self): signal.signal(signal.SIGINT, signal.SIG_DFL) # allow ctrl-c sys.exit(self.app.exec_())
class Test: def __init__(self): request = QNetworkRequest(QUrl("http://www.riverbankcomputing.co.uk/news")) self.manager = QNetworkAccessManager() self.manager.finished.connect(self.handleReply) self.manager.get(request) def handleReply(self, reply): print reply.readAll() print reply.error() QCoreApplication.quit() if __name__ == "__main__": app = QCoreApplication(sys.argv) test = Test() sys.exit(app.exec_()) ['DeleteOperation', 'GetOperation', 'HeadOperation', 'Operation', 'PostOperation', 'PutOperation', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'authenticationRequired', 'blockSignals', 'cache', 'childEvent', 'children', 'connect', 'connectNotify', 'cookieJar', 'createRequest', 'customEvent', 'deleteLater', 'deleteResource', 'destroyed', 'disconnect', 'disconnectNotify', 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames', 'emit', 'event', 'eventFilter', 'findChild', 'findChildren', 'finished', 'get', 'head', 'inherits', 'installEventFilter', 'isWidgetType', 'killTimer', 'metaObject', 'moveToThread', 'objectName', 'parent', 'post', 'property', 'proxy', 'proxyAuthenticationRequired', 'proxyFactory', 'put', 'pyqtConfigure', 'receivers', 'removeEventFilter', 'sender', 'setCache', 'setCookieJar', 'setObjectName', 'setParent', 'setProperty', 'setProxy', 'setProxyFactory', 'signalsBlocked', 'sslErrors', 'startTimer', 'staticMetaObject', 'thread', 'timerEvent', 'tr', 'trUtf8'] ['Append', 'AuthenticationRequiredError', 'ConnectionRefusedError', 'ContentAccessDenied', 'ContentNotFoundError', 'ContentOperationNotPermittedError', 'ContentReSendError', 'HostNotFoundError', 'NetworkError', 'NoError', 'NotOpen', 'OpenMode', 'OpenModeFlag', 'OperationCanceledError', 'ProtocolFailure', 'ProtocolInvalidOperationError', 'ProtocolUnknownError', 'ProxyAuthenticationRequiredError', 'ProxyConnectionClosedError', 'ProxyConnectionRefusedError', 'ProxyNotFoundError', 'ProxyTimeoutError', 'ReadOnly', 'ReadWrite', 'RemoteHostClosedError', 'SslHandshakeFailedError', 'Text', 'TimeoutError', 'Truncate', 'Unbuffered', 'UnknownContentError', 'UnknownNetworkError', 'UnknownProxyError', 'WriteOnly', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'abort', 'aboutToClose', 'atEnd', 'attribute', 'blockSignals', 'bytesAvailable', 'bytesToWrite', 'bytesWritten', 'canReadLine', 'childEvent', 'children', 'close', 'connect', 'connectNotify', 'customEvent', 'deleteLater', 'destroyed', 'disconnect', 'disconnectNotify', 'downloadProgress', 'dumpObjectInfo', 'dumpObjectTree', 'dynamicPropertyNames', 'emit', 'error', 'errorString', 'event', 'eventFilter', 'findChild', 'findChildren', 'finished', 'getChar', 'hasRawHeader', 'header', 'ignoreSslErrors', 'inherits', 'installEventFilter', 'isFinished', 'isOpen', 'isReadable', 'isRunning', 'isSequential', 'isTextModeEnabled', 'isWidgetType', 'isWritable', 'killTimer', 'manager', 'metaDataChanged', 'metaObject', 'moveToThread', 'objectName', 'open', 'openMode', 'operation', 'parent', 'peek', 'pos', 'property', 'putChar', 'pyqtConfigure', 'rawHeader', 'rawHeaderList', 'read', 'readAll', 'readBufferSize', 'readChannelFinished', 'readData', 'readLine', 'readLineData', 'readyRead', 'receivers', 'removeEventFilter', 'request', 'reset', 'seek', 'sender', 'setAttribute', 'setError', 'setErrorString', 'setHeader', 'setObjectName', 'setOpenMode', 'setOperation', 'setParent', 'setProperty', 'setRawHeader', 'setReadBufferSize', 'setRequest', 'setSslConfiguration', 'setTextModeEnabled', 'setUrl', 'signalsBlocked', 'size', 'sslConfiguration', 'sslErrors', 'startTimer', 'staticMetaObject', 'thread', 'timerEvent', 'tr', 'trUtf8', 'ungetChar', 'uploadProgress', 'url', 'waitForBytesWritten', 'waitForReadyRead', 'write', 'writeData']
else: print 'cdnotify: unknown disc type (%i)' % disc_type elif self._status == -1: print 'cdnotify: status -1' else: print 'cdnotify: unknown status (%i)' % self._status if __name__ == '__main__': from PyQt4.QtCore import QCoreApplication a = QCoreApplication([]) drive = Drive() def cb_audio(): print 'inserted audio' def cb_data(): print 'inserted data' def cb_eject(): print 'ejected' QObject.connect(drive, SIGNAL('audioInserted()'), cb_audio) QObject.connect(drive, SIGNAL('dataInserted()'), cb_data) QObject.connect(drive, SIGNAL('ejected()'), cb_eject) a.exec_()
def getFullName(self, exchange, ticker): return self.cachedData(exchange, ticker, "name") def getMarketCap(self, exchange, ticker): return self.cachedData(exchange, ticker, "mc") def getPrice(self, exchange, ticker): return self.cachedData(exchange, ticker, "l_cur") def getColor(self, exchange, ticker): return self.cachedData(exchange, ticker, "ccol") def getPeRatio(self, exchange, ticker): return self.cachedData(exchange, ticker, "pe") def getDelay(self, exchange, ticker): return self.cachedData(exchange, ticker, "delay") def getVolume(self, exchange, ticker): return self.cachedData(exchange, ticker, "vo") def getAverageVolume(self, exchange, ticker): return self.cachedData(exchange, ticker, "avvo") if __name__ == '__main__': qtApp = QCoreApplication(sys.argv) app = CachedStockQuoter() app.updateCache("NYSE", ["MCD", "GE"]) app.updateCache("HKG", ["0811", "0927", "0888", "3918", "0050", "1991"]) sys.exit(qtApp.exec_())
t = QThread() w = MTWorker() heart = QTimer() def check_pulse(): if not t.isRunning(): heart.stop() app.quit() # exit the application when the thread stops heart.timeout.connect(check_pulse) # this is boiler plate, clean-up and quit w.finished.connect(w.deleteLater) w.finished.connect(t.quit) app.aboutToQuit.connect(t.wait) # move worker to thread w.moveToThread(t) # prevent premature exit, the heart beats after every event! heart.start(0) # start worker thread (event loop), and the worker t.start() w.start.emit() # main application thread (event loop) logger.info('starting application') sys.exit(app.exec_())
import signal from PyQt4.QtCore import QCoreApplication, QTimer from connectivity import QTurnSocket if __name__ == '__main__': import logging logging.getLogger().setLevel(logging.DEBUG) def sigint_handler(*args): QCoreApplication.quit() print("Testing turnclient") app = QCoreApplication([]) timer = QTimer() signal.signal(signal.SIGINT, sigint_handler) timer.start(500) timer.timeout.connect(lambda: None) c = QTurnSocket() c.run() app.exec_()
def loop(): DBusQtMainLoop(set_as_default=True) app = QCoreApplication([]) ctl = SleepCtl() app.exec_()