def _initializeQApp5(self): try: from PyQt5.QtCore import QCoreApplication self.app = QCoreApplication([]) return except ImportError: pass
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 __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) self.loaded = False self.app = QCoreApplication([])
def runow(): try: app = QCoreApplication(sys.argv) me = BatchOrder(cf) me.start() #sys.exit(app.exec_()) except BaseException, e: logger.exception(e)
def qt4_plugins_dir(): from PyQt4.QtCore import QCoreApplication app = QCoreApplication([]) qt4_plugin_dirs = map(unicode, app.libraryPaths()) if not qt4_plugin_dirs: return for d in qt4_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds
def main(argv): app = QCoreApplication(argv) discovery = TrickplayDiscovery() debugger = CLDebuger() try: debugger.start(discovery) except (KeyboardInterrupt, EOFError): sys.exit()
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 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 __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 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 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 _initializeQApp4(self): try: # QtGui should be imported _before_ QtCore package. # This is done for the QWidget references from QtCore (such as QSignalMapper). Known bug in PyQt 4.7+ # Causes "TypeError: C++ type 'QWidget*' is not supported as a native Qt signal type" import PyQt4.QtGui except ImportError: pass # manually instantiate and keep reference to singleton QCoreApplication (we don't want it to be deleted during the introspection) # use QCoreApplication instead of QApplication to avoid blinking app in Dock on Mac OS try: from PyQt4.QtCore import QCoreApplication self.app = QCoreApplication([]) return except ImportError: pass
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 __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) if QCoreApplication.instance() is None: # Application Object has not been started yet self.qApp = QCoreApplication([]) self._ownApp = True else: self.qApp = QCoreApplication.instance() self._ownApp = False self._blockApp = None posixbase.PosixReactorBase.__init__(self)
def __init__(self): self._reads = {} self._writes = {} self._timer = QTimer() self._timer.setSingleShot(True) if QCoreApplication.startingUp(): self.qApp = QCoreApplication([]) self._ownApp = True else: self.qApp = QCoreApplication.instance() self._ownApp = False self._blockApp = None self._readWriteQ = [] """ some debugging instrumentation """ self._doSomethingCount = 0 PosixReactorBase.__init__(self)
def main(): """Function to test functionality.""" import sys from PyQt4.QtCore import QCoreApplication conf = """ p1 = 1 [mysection] p2 = 2 [[mysubsection]] p3 = 3.14 """ app = QCoreApplication(sys.argv) app.setApplicationName('configtest') app.setOrganizationName('foo') config = configobj.ConfigObj(conf.split('\n')) settings = to_QSettings(config) config2 = from_QSettings(settings) print(config == config2)
def setUp(self): self.qApp = QCoreApplication(['test_app']) self.table_model = TableModel() self.state_gui_model = StateGuiModel({}) table_index_model_0 = TableIndexModel('LOQ74044', '', '', '', '', '', '', '', '', '', '', '') table_index_model_1 = TableIndexModel('LOQ74044', '', '', '', '', '', '', '', '', '', '', '') self.table_model.add_table_entry(0, table_index_model_0) self.table_model.add_table_entry(1, table_index_model_1) self.table_model.wait_for_file_finding_done() self.qApp.processEvents() self.fake_state = mock.MagicMock(spec=State) self.gui_state_director_instance = mock.MagicMock() self.gui_state_director_instance.create_state.return_value = self.fake_state self.patcher = mock.patch('sans.gui_logic.models.create_state.GuiStateDirector') self.addCleanup(self.patcher.stop) self.gui_state_director = self.patcher.start() self.gui_state_director.return_value = self.gui_state_director_instance
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 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 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 __init__(self, timeout=2000, size=2**20): 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) self.sock.waitForBytesWritten() self.is_connected = True self.timeout = timeout atexit.register(self.close)
def setUpClass(cls): cls.qApp = QCoreApplication(['test_app'])
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_()
super(MTWorker, self).__init__() self.start.connect(self.doWork) @pyqtSlot() def doWork(self): logging.getLogger().info('doWork slot triggered, doing some work!') self.finished.emit() if __name__ == '__main__': # set up logger so we can see the thread activity logging.basicConfig(format='%(threadName)s: %(message)s', level=logging.DEBUG) logger = logging.getLogger() app = QCoreApplication(sys.argv) 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)
def testSmewtDaemon(self): # we need to remove traces of previous test runs, even though we're supposed to have cleaned it after the test, # a previous run of the test that failed might not have done that os.system('rm -fr ~/.config/Falafelton_tmp') os.system('rm -fr /tmp/smewt_test_daemon') import smewt orgname = smewt.ORG_NAME appname = smewt.APP_NAME smewt.ORG_NAME = 'Falafelton_tmp' smewt.APP_NAME = 'Smewt_tmp' from PyQt4.QtCore import QCoreApplication app = QCoreApplication([]) app.setOrganizationName(smewt.ORG_NAME) app.setOrganizationDomain('smewt.com') app.setApplicationName(smewt.APP_NAME) smewtd = SmewtDaemon() # create fake database cmds = '''mkdir -p /tmp/smewt_test_daemon/Monk touch /tmp/smewt_test_daemon/Monk/Monk.2x05.Mr.Monk.And.The.Very,.Very.Old.Man.DVDRip.XviD-MEDiEVAL.[tvu.org.ru].avi touch /tmp/smewt_test_daemon/Monk/Monk.2x05.Mr.Monk.And.The.Very,.Very.Old.Man.DVDRip.XviD-MEDiEVAL.[tvu.org.ru].English.srt ''' for cmd in cmds.split('\n'): os.system(cmd.strip()) smewtd.episodeCollection.folders = { '/tmp/smewt_test_daemon': True } # make sure we don't have a residual collection from previous test runs self.assertEqual(len(list(smewtd.database.nodes())), 0) # initial import of the collection smewtd.episodeCollection.rescan() smewtd.taskManager.queue.join() # wait for all import tasks to finish #smewtd.database.display_graph() self.collectionTestIncomplete(smewtd.database) # update collection, as we haven't changed anything it should be the same smewtd.episodeCollection.update() smewtd.taskManager.queue.join() # wait for all import tasks to finish #smewtd.database.display_graph() self.collectionTestIncomplete(smewtd.database) # fully rescan collection, should still be the same smewtd.episodeCollection.rescan() smewtd.taskManager.queue.join() # wait for all import tasks to finish #smewtd.database.display_graph() self.collectionTestIncomplete(smewtd.database) # add some more files cmds = '''mkdir -p /tmp/smewt_test_daemon/Monk touch /tmp/smewt_test_daemon/Monk/Monk.2x06.Mr.Monk.Goes.To.The.Theater.DVDRip.XviD-MEDiEVAL.[tvu.org.ru].avi touch /tmp/smewt_test_daemon/Monk/Monk.2x06.Mr.Monk.Goes.To.The.Theater.DVDRip.XviD-MEDiEVAL.[tvu.org.ru].English.srt ''' for cmd in cmds.split('\n'): os.system(cmd.strip()) # update collection smewtd.episodeCollection.update() smewtd.taskManager.queue.join() # wait for all import tasks to finish #smewtd.database.display_graph() self.collectionTest(smewtd.database) # clean up our mess before we exit os.system('rm -fr ~/.config/Falafelton_tmp') os.system('rm -fr /tmp/smewt_test_daemon') smewt.ORG_NAME = orgname smewt.APP_NAME = appname
def setUp(self): self.app = QCoreApplication([]) QTimer.singleShot(20000, self.app.exit)
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_()
def setUp(self): self.success_callback = mock.MagicMock() self.success_callback_1 = mock.MagicMock() self.error_callback = mock.MagicMock() self.work_handler = WorkHandler() self.qApp = QCoreApplication(['test_app'])
def setUp(self): self.app = QCoreApplication([])