Esempio n. 1
1
    def __init__(self, address, *, prefix=b'',
                 loop=None, zmq=None, zmq_asyncio=None,
                 deserializer=pickle.loads):
        if isinstance(prefix, str):
            raise ValueError("prefix must be bytes, not string")
        if b' ' in prefix:
            raise ValueError("prefix {!r} may not contain b' '".format(prefix))
        self._prefix = prefix
        if zmq is None:
            import zmq
        if zmq_asyncio is None:
            import zmq.asyncio as zmq_asyncio
        if isinstance(address, str):
            address = address.split(':', maxsplit=1)
        self._deserializer = deserializer
        self.address = (address[0], int(address[1]))

        if loop is None:
            loop = zmq_asyncio.ZMQEventLoop()
        self.loop = loop
        asyncio.set_event_loop(self.loop)
        self._context = zmq_asyncio.Context()
        self._socket = self._context.socket(zmq.SUB)
        url = "tcp://%s:%d" % self.address
        self._socket.connect(url)
        self._socket.setsockopt_string(zmq.SUBSCRIBE, "")
        self._task = None

        super().__init__()
Esempio n. 2
0
def start_listening(bot=None, loop=None, name="", port=8000, certfile=None, webhookReceiver=BaseHTTPRequestHandler, friendlyName="UNKNOWN"):
    if loop:
        asyncio.set_event_loop(loop)

    if bot:
        webhookReceiver._bot = bot

    try:
        httpd = HTTPServer((name, port), webhookReceiver)

        httpd.socket = ssl.wrap_socket(
          httpd.socket,
          certfile=certfile,
          server_side=True)

        sa = httpd.socket.getsockname()

        message = "sink: {} : {}:{}...".format(friendlyName, sa[0], sa[1])
        print(message)

        httpd.serve_forever()

    except OSError as e:
        message = "SINK: {} : {}:{} : {}".format(friendlyName, name, port, e)
        print(message)
        logging.error(message)
        logging.exception(e)

        try:
            httpd.socket.close()
        except Exception as e:
            pass

    except KeyboardInterrupt:
        httpd.socket.close()
Esempio n. 3
0
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.transport = unittest.mock.Mock()
        self.stream = aiohttp.StreamParser(loop=self.loop)
        self.response = HttpResponse('get', 'http://python.org')
Esempio n. 4
0
 def test_ctor_with_default_loop(self):
     loop = asyncio.new_event_loop()
     asyncio.set_event_loop(loop)
     self.addCleanup(loop.close)
     self.addCleanup(asyncio.set_event_loop, None)
     conn = aiohttp.BaseConnector()
     self.assertIs(loop, conn._loop)
def launcher(num, sem):
	print("Starting:", num)
	asyncio.set_event_loop(loop)

	loop.run_until_complete(recv_and_process(num))

	sem.release()
Esempio n. 6
0
def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from asyncio.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        import ssl
        # TODO: take cert/key from args as well.
        here = os.path.join(os.path.dirname(__file__), '..', 'tests')
        sslctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
        sslctx.options |= ssl.OP_NO_SSLv2
        sslctx.load_cert_chain(
            certfile=os.path.join(here, 'ssl_cert.pem'),
            keyfile=os.path.join(here, 'ssl_key.pem'))
    cache = Cache(loop)
    task = asyncio.streams.start_server(cache.handle_client,
                                        args.host, args.port,
                                        ssl=sslctx, loop=loop)
    svr = loop.run_until_complete(task)
    for sock in svr.sockets:
        logging.info('socket %s', sock.getsockname())
    try:
        loop.run_forever()
    finally:
        loop.close()
Esempio n. 7
0
def main():
    # create the Application
    app = QtWidgets.QApplication(sys.argv)

    # create the event loop
    event_loop = QEventLoop(app)
    asyncio.set_event_loop(event_loop)

    # Create the Gui
    main_window = MainWindow()
    # plugins to include different websites (and listeners?)
    plugin_manager = PluginManager()
    plugin_manager.register_main_window(main_window)

    # User Settings
    settings_manager = SettingsManager()
    settings_manager.register_main_window(main_window)
    settings_manager.register_plugin_manager(plugin_manager)

    main_window.show()
    try:
        event_loop.run_forever()
    except KeyboardInterrupt:
        pass
    app.deleteLater()
    plugin_manager.terminate_plugins()
    event_loop.close()
    sys.exit()
Esempio n. 8
0
 def test_ctor_noloop(self):
     try:
         asyncio.set_event_loop(self.loop)
         q = asyncio.Queue()
         self.assertIs(q._loop, self.loop)
     finally:
         asyncio.set_event_loop(None)
Esempio n. 9
0
def test_mitmweb(event_loop, tdata):
    asyncio.set_event_loop(event_loop)
    main.mitmweb([
        "--no-web-open-browser",
        "-s", tdata.path(shutdown_script),
        "-q", "-p", "0",
    ])
Esempio n. 10
0
 def add_task(self, task_id):
     try:
         loop = asyncio.get_event_loop()
     except RuntimeError:
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
     loop.run_until_complete(self._new_task(task_id))
Esempio n. 11
0
 def tearDown(self):
     if self.client:
         self.close(self.client)
     if self.server:
         self.close(self.server)
     self.loop.close()
     asyncio.set_event_loop(None)
Esempio n. 12
0
            def run_in_loop(s_args, s_kwargs, c_args, c_kwargs):

                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(None)

                server = aioftp.Server(*s_args, loop=loop, **s_kwargs)
                client = aioftp.Client(*c_args, loop=loop, **c_kwargs)

                coro = asyncio.coroutine(f)
                try:

                    loop.run_until_complete(coro(loop, client, server))

                finally:

                    if hasattr(server, "server"):

                        server.close()
                        loop.run_until_complete(server.wait_closed())

                    if hasattr(client, "writer"):

                        client.close()

                    loop.close()
Esempio n. 13
0
 def setUp(self):
     # This simulates the effect of an asyncio test harness like
     # pytest-asyncio.
     self.orig_loop = asyncio.get_event_loop()
     self.new_loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.new_loop)
     super(GetNewIOLoopTest, self).setUp()
Esempio n. 14
0
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(None)
     self.database = 'aiopg'
     self.user = '******'
     self.host = '127.0.0.1'
     self.password = '******'
Esempio n. 15
0
File: cli.py Progetto: cirix/dcos
def run_loop(action, options):
    assert callable(action)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    print_header('START {}'.format(action.__name__))
    try:
        config = backend.get_config()
        cli_delegate = CliDelegate()
        result = loop.run_until_complete(action(config, block=True, async_delegate=cli_delegate, options=options))
        pp = PrettyPrint(result)
        pp.stage_name = action.__name__
        pp.beautify('print_data')

    finally:
        loop.close()
    exitcode = 0
    for host_result in result:
        for command_result in host_result:
            for host, process_result in command_result.items():
                if process_result['returncode'] != 0:
                    exitcode += 1
    print_header('ACTION {} COMPLETE'.format(action.__name__))
    pp.print_summary()
    return exitcode
Esempio n. 16
0
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())
Esempio n. 17
0
 def setUp(self):
     self.transport = Mock()
     self.transport.write = self._write
     self.responses = []
     self._old_loop = asyncio.get_event_loop()
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
Esempio n. 18
0
File: test.py Progetto: omo/cdjbot
 def setUp(self):
     self._bot = make_mock_bot()
     self._store = make_clean_mongo_store()
     self._looper = FakeLooper()
     # http://stackoverflow.com/questions/23033939/how-to-test-python-3-4-asyncio-code
     self._loop = asyncio.new_event_loop()
     asyncio.set_event_loop(None)
Esempio n. 19
0
    def test_global_loop(self):
        asyncio.set_event_loop(self.loop)

        conn = self.loop.run_until_complete(self.create_connection(
            ('localhost', self.redis_port), db=0))
        self.assertEqual(conn.db, 0)
        self.assertIs(conn._loop, self.loop)
Esempio n. 20
0
    def test_wait_with_global_loop(self):

        def gen():
            when = yield
            self.assertAlmostEqual(0.01, when)
            when = yield 0
            self.assertAlmostEqual(0.015, when)
            yield 0.015

        loop = test_utils.TestLoop(gen)
        self.addCleanup(loop.close)

        a = asyncio.Task(asyncio.sleep(0.01, loop=loop), loop=loop)
        b = asyncio.Task(asyncio.sleep(0.015, loop=loop), loop=loop)

        @asyncio.coroutine
        def foo():
            done, pending = yield from asyncio.wait([b, a])
            self.assertEqual(done, set([a, b]))
            self.assertEqual(pending, set())
            return 42

        asyncio.set_event_loop(loop)
        try:
            res = loop.run_until_complete(
                asyncio.Task(foo(), loop=loop))
        finally:
            asyncio.set_event_loop(None)

        self.assertEqual(res, 42)
Esempio n. 21
0
 def setUp(self):
     self.loop = aiozmq.ZmqEventLoop()
     asyncio.set_event_loop(None)
     self.client = self.server = None
     self.queue = asyncio.Queue(loop=self.loop)
     self.err_queue = asyncio.Queue(loop=self.loop)
     self.loop.set_exception_handler(self.exception_handler)
Esempio n. 22
0
def start_listening(bot=None, loop=None, name="", port=8000, certfile=None, webhookReceiver=BaseHTTPRequestHandler, friendlyName="UNKNOWN"):
    if loop:
        asyncio.set_event_loop(loop)

    if bot:
        webhookReceiver._bot = bot

    try:
        httpd = HTTPServer((name, port), webhookReceiver)

        httpd.socket = ssl.wrap_socket(
          httpd.socket,
          certfile=certfile,
          server_side=True)

        sa = httpd.socket.getsockname()
        print(_("listener: {} : sink on {}, port {}...").format(friendlyName, sa[0], sa[1]))

        httpd.serve_forever()
    except IOError:
        # do not run sink without https!
        print(_("listener: {} : pem file possibly missing or broken (== '{}')").format(friendlyName, certfile))
        httpd.socket.close()
    except OSError as e:
        # Could not connect to HTTPServer!
        print(_("listener: {} : requested access could not be assigned. Is something else using that port? (== '{}:{}')").format(friendlyName, name, port))
    except KeyboardInterrupt:
        httpd.socket.close()
Esempio n. 23
0
    def start(self):
        assert not self._started
        self._started = True

        up_read, up_write = os.pipe()
        down_read, down_write = os.pipe()
        args, sock = self.args, self.sock

        pid = os.fork()
        if pid:
            # parent
            os.close(up_read)
            os.close(down_write)
            asyncio.async(self.connect(pid, up_write, down_read))
        else:
            # child
            os.close(up_write)
            os.close(down_read)

            # cleanup after fork
            asyncio.set_event_loop(None)

            # setup process
            process = ChildProcess(up_read, down_write, args, sock)
            process.start()
Esempio n. 24
0
    def tearDown(self):
        self.loop.close()

        if getattr(self.loop, '_debug_cc', False):
            gc.collect()
            gc.collect()
            gc.collect()

            self.assertEqual(self.loop._debug_cb_handles_count, 0)
            self.assertEqual(self.loop._debug_cb_timer_handles_count, 0)
            self.assertEqual(self.loop._debug_stream_write_ctx_cnt, 0)

            for h_name, h_cnt in self.loop._debug_handles_current.items():
                with self.subTest('Alive handle after test',
                                  handle_name=h_name):
                    self.assertEqual(h_cnt, 0)

            for h_name, h_cnt in self.loop._debug_handles_total.items():
                with self.subTest('Total/closed handles',
                                  handle_name=h_name):
                    self.assertEqual(
                        h_cnt, self.loop._debug_handles_closed[h_name])

        asyncio.set_event_loop(None)
        self.loop = None
Esempio n. 25
0
        def unset_event_loop():
            """ Unset the current loop as the current context's event loop

            This prevents any other tasklets/library from inadvertantly using
            this tasklets event loop.
            """
            asyncio.set_event_loop(None)
Esempio n. 26
0
        def run(self):
            """
                The thread function. This represents a new thread of execution.
            """
            while self.should_run is True:
                if self.discord_connection is not None:
                    self.discord_connection.logout()
                    print("!!! Attempting to reconnect.")

                self.loop = asyncio.new_event_loop()
                asyncio.set_event_loop(self.loop)

                self.discord_connection = discord.Client()

                @self.discord_connection.event
                @asyncio.coroutine
                def on_message(message):
                    if message.type is discord.MessageType.default:
                        self.outgoing_lock.acquire()
                        self.outgoing_messages.append(message)
                        self.outgoing_lock.release()

                try:
                    self.discord_connection.loop.create_task(self.process_input_messages())
                    self.discord_connection.run(self.configuration["token"])
                except Exception as e:
                    print("!!! Discord connection threw an exception: %s" % str(e))
Esempio n. 27
0
 def _set_event_loop(self):
     if self.run_async:
         self._event_loop = asyncio.get_event_loop()
     else:
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
         self._event_loop = loop
Esempio n. 28
0
        def set_event_loop():
            """ Set the current loop as the current context's event loop

            This allows callers to use asyncio without passing in the explicit
            event loop.
            """
            asyncio.set_event_loop(self)
Esempio n. 29
0
    def test_wait_for_with_global_loop(self):

        def gen():
            when = yield
            self.assertAlmostEqual(0.2, when)
            when = yield 0
            self.assertAlmostEqual(0.01, when)
            yield 0.01

        loop = test_utils.TestLoop(gen)
        self.addCleanup(loop.close)

        @asyncio.coroutine
        def foo():
            yield from asyncio.sleep(0.2, loop=loop)
            return 'done'

        asyncio.set_event_loop(loop)
        try:
            fut = asyncio.Task(foo(), loop=loop)
            with self.assertRaises(asyncio.TimeoutError):
                loop.run_until_complete(asyncio.wait_for(fut, 0.01))
        finally:
            asyncio.set_event_loop(None)

        self.assertAlmostEqual(0.01, loop.time())
        self.assertTrue(fut.done())
        self.assertTrue(fut.cancelled())
Esempio n. 30
0
def demo():
    # --------- Example 1 ---------

    # asyncio provides a run() function to execute an async def function and all other coroutines called from there,
    # like sleep() in the main() function. In practice, most of your Asyncio-based code will use the run() function shown
    # here
    # asyncio.run(main())

    # --------- Example 2 ---------

    # 1- You need a loop instance before you can run any coroutines, and this is how you get one. In fact, anywhere you call
    # it, get_event_loop() will give you the same loop instance each time, as long as you’re using only a single thread.2
    # If you’re inside an async def function, you should call asyncio.get_running_loop() instead, which always gives you
    # what you expect
    loop = asyncio.get_event_loop()

    # 2- Your coroutine function will not be executed until you do this. We say that create_task() schedules your
    # coroutine to be run on the loop.3 The returned task object can be used to monitor the status of the task (for
    # example, whether it is still running or has completed), and can also be used to obtain a result value from your
    # completed coroutine. You can cancel the task with task.cancel().
    task = loop.create_task(main())

    # 3- This call will block the current thread, which will usually be the main thread. Note that run_until_complete()
    # will keep the loop running only until the given task completes—but all other tasks scheduled on the loop will also
    # run while the loop is running.
    # Internally, asyncio.run() calls run_until_complete() for you and therefore blocks
    # the main thread in the same way. When the “main” part of the program unblocks, either due to a process signal being
    # received or the loop being stopped by some code calling loop.stop(), the code after run_until_complete() will run.
    loop.run_until_complete(task)

    # 4- The standard idiom as shown here is to gather the still-pending tasks, cancel them, and then use
    # loop.run_until_complete() again until those tasks are done. gather() is the method for doing the gathering.
    # Note that asyncio.run() will do all of the cancelling, gathering, and waiting for pending tasks to finish up.
    pending = asyncio.all_tasks(loop=loop)
    for task in pending:
        task.cancel()

    group = asyncio.gather(*pending, return_exceptions=True)
    loop.run_until_complete(group)

    # 5- loop.close() is usually the final action: it must be called on a stopped loop, and it will clear all queues and
    # shut down the executor. A stopped loop can be restarted, but a closed loop is gone for good.
    # Internally, asyncio.run() will close the loop before returning. This is fine because asyncio.run() creates a new
    # event loop every time you call it.
    loop.close()

    # If you use asyncio.run() (see example 1), none of these steps are necessary: they are all done for you.

    # --------- Example 3 ---------

    def blocking():
        time.sleep(0.5)
        print(f"{time.ctime()} Hello from a thread!")

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    task = loop.create_task(main())

    loop.run_in_executor(None, blocking)
    loop.run_until_complete(task)

    pending = asyncio.all_tasks(loop=loop)
    for task in pending:
        task.cancel()
    group = asyncio.gather(*pending, return_exceptions=True)
    loop.run_until_complete(group)
    loop.close()

    # --------- Example 4 ---------
    async def f(delay):
        await asyncio.sleep(1 / delay)
        return delay

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    for i in range(10):
        loop.create_task(f(i))
    pending = asyncio.all_tasks(loop=loop)

    # Without return_exceptions=True, the ZeroDivisionError would be raised from run_until_complete(), stopping the
    # loop and thus preventing the other tasks from finishing.
    group = asyncio.gather(*pending, return_exceptions=True)

    results = loop.run_until_complete(group)
    print(f'Results: {results}')
    loop.close()
def launch_query(c):
    asyncio.set_event_loop(asyncio.new_event_loop())
    twint.run.Search(c)
Esempio n. 32
0
import asyncio

import uvloop

from sanic import Sanic, response

app = Sanic("Example")


@app.route("/")
async def test(request):
    return response.json({"answer": "42"})


async def main():
    server = await app.create_server(port=8000,
                                     host="0.0.0.0",
                                     return_asyncio_server=True)

    if server is None:
        return

    await server.startup()
    await server.serve_forever()


if __name__ == "__main__":
    asyncio.set_event_loop(uvloop.new_event_loop())
    asyncio.run(main())
 def start_socket_server(self):
   asyncio.set_event_loop(self.loop)
   self.loop.run_until_complete(self.socket_server)
   self.loop.run_forever()
Esempio n. 34
0
def test_apprise_asyncio_runtime_error():
    """
    API: Apprise() AsyncIO RuntimeError handling

    """
    class GoodNotification(NotifyBase):
        def __init__(self, **kwargs):
            super(GoodNotification, self).__init__(
                notify_format=NotifyFormat.HTML, **kwargs)

        def url(self, **kwargs):
            # Support URL
            return ''

        def send(self, **kwargs):
            # Pretend everything is okay
            return True

        @staticmethod
        def parse_url(url, *args, **kwargs):
            # always parseable
            return NotifyBase.parse_url(url, verify_host=False)

    # Store our good notification in our schema map
    SCHEMA_MAP['good'] = GoodNotification

    # Create ourselves an Apprise object
    a = Apprise()

    # Add a few entries
    for _ in range(25):
        a.add('good://')

    # Python v3.6 and lower can't handle situations gracefully when an
    # event_loop isn't already established(). Test that Apprise can handle
    # these situations
    import asyncio

    # Get our event loop
    loop = asyncio.get_event_loop()

    # Adjust out event loop to not point at anything
    asyncio.set_event_loop(None)

    # With the event loop inactive, we'll fail trying to get the active loop
    with pytest.raises(RuntimeError):
        asyncio.get_event_loop()

    try:
        # Below, we internally will throw a RuntimeError() since there will
        # be no active event_loop in place. However internally it will be smart
        # enough to create a new event loop and continue...
        assert a.notify(title="title", body="body") is True

        # Verify we have an active event loop
        new_loop = asyncio.get_event_loop()

        # We didn't throw an exception above; thus we have an event loop at
        # this point
        assert new_loop

        # Close off the internal loop created inside a.notify()
        new_loop.close()

    finally:
        # Restore our event loop (in the event the above test failed)
        asyncio.set_event_loop(loop)
Esempio n. 35
0
 def setUp(self):
     """Set up test class."""
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
Esempio n. 36
0
 def _start_background_loop(loop):
     asyncio.set_event_loop(loop)
     loop.run_forever()
Esempio n. 37
0
def new_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    yield loop
    loop.close()
Esempio n. 38
0
 def _run_event_loop():
     asyncio.set_event_loop(loop)
     loop.run_forever()
Esempio n. 39
0
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
     self.loop.set_default_executor(self.executor)
     asyncio.set_event_loop(None)
Esempio n. 40
0
    def setup(self, socket_type, complete_or_error_queue):
        """Setup the asyncio event loop.

        Args:
            socket_type (int from zmq.*): One of zmq.DEALER or zmq.ROUTER
            complete_or_error_queue (queue.Queue): A way to propagate errors
                back to the calling thread. Needed since this function is
                directly used in Thread.

        Returns:
            None
        """
        try:
            if self._secured:
                if self._server_public_key is None or \
                        self._server_private_key is None:
                    raise LocalConfigurationError(
                        "Attempting to start socket in secure mode, "
                        "but complete server keys were not provided")

            self._event_loop = zmq.asyncio.ZMQEventLoop()
            asyncio.set_event_loop(self._event_loop)
            self._context = zmq.asyncio.Context()
            self._socket = self._context.socket(socket_type)

            if socket_type == zmq.DEALER:
                self._socket.identity = "{}-{}".format(
                    self._zmq_identity,
                    hashlib.sha512(uuid.uuid4().hex.encode()).hexdigest()
                    [:23]).encode('ascii')

                if self._secured:
                    # Generate ephemeral certificates for this connection

                    pubkey, secretkey = zmq.curve_keypair()
                    self._socket.curve_publickey = pubkey
                    self._socket.curve_secretkey = secretkey
                    self._socket.curve_serverkey = self._server_public_key

                self._socket.connect(self._address)
            elif socket_type == zmq.ROUTER:
                if self._secured:
                    auth = AsyncioAuthenticator(self._context)
                    self._auth = auth
                    auth.start()
                    auth.configure_curve(domain='*',
                                         location=zmq.auth.CURVE_ALLOW_ANY)

                    self._socket.curve_secretkey = self._server_private_key
                    self._socket.curve_publickey = self._server_public_key
                    self._socket.curve_server = True

                try:
                    self._socket.bind(self._address)
                except zmq.error.ZMQError as e:
                    raise LocalConfigurationError(
                        "Can't bind to {}: {}".format(self._address, str(e)))
                else:
                    LOGGER.info("Listening on %s", self._address)

            self._dispatcher.add_send_message(self._connection,
                                              self.send_message)
            self._dispatcher.add_send_last_message(self._connection,
                                                   self.send_last_message)

            asyncio.ensure_future(self._receive_message(),
                                  loop=self._event_loop)
            if self._monitor:
                self._monitor_fd = "inproc://monitor.s-{}".format(
                    _generate_id()[0:5])
                self._monitor_sock = self._socket.get_monitor_socket(
                    zmq.EVENT_DISCONNECTED, addr=self._monitor_fd)
                asyncio.ensure_future(self._monitor_disconnects(),
                                      loop=self._event_loop)

        except Exception as e:
            # Put the exception on the queue where in start we are waiting
            # for it.
            complete_or_error_queue.put_nowait(e)
            raise

        if self._heartbeat:
            asyncio.ensure_future(self._do_heartbeat(), loop=self._event_loop)

        # Put a 'complete with the setup tasks' sentinel on the queue.
        complete_or_error_queue.put_nowait(_STARTUP_COMPLETE_SENTINEL)

        asyncio.ensure_future(self._notify_started(), loop=self._event_loop)

        self._event_loop.run_forever()
        # event_loop.stop called elsewhere will cause the loop to break out
        # of run_forever then it can be closed and the context destroyed.
        self._event_loop.close()
        self._socket.close(linger=0)
        if self._monitor:
            self._monitor_sock.close(linger=0)
        self._context.destroy(linger=0)
def start_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    application = tornado.web.Application([(r'/ws', WSHandler),])
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(__SOCKET_PORT)
    tornado.ioloop.IOLoop.instance().start()
Esempio n. 42
0
    def __init__(self, loop, config):

        self.ob_constant = OD_TICK_TIMER
        self.bl_constant = BALANCE_TICK_TIMER
        self.trade_constant = TRADE_TICK_TIMER

        self.stop_tick_time = datetime.datetime.now() + datetime.timedelta(
            seconds=TICK_TIMER)
        self.orderbook_tick_time = datetime.datetime.now(
        ) + datetime.timedelta(seconds=self.ob_constant)
        self.balance_tick_time = datetime.datetime.now() + datetime.timedelta(
            seconds=self.bl_constant)
        self.trade_tick_time = datetime.datetime.now() + datetime.timedelta(
            seconds=self.trade_constant)
        self.info_tick_time = datetime.datetime.now() + datetime.timedelta(
            seconds=INFO_TIMER)

        self.config = config
        self.orderbook_count = 0
        self.pair_info = dict()
        self.logger = None
        if 'logger' in self.config.keys():
            self.logger = self.config['logger']

        self.exhange = config['exchange']
        self.is_auth = False
        self.name = '[ccxt %s]' % self.exhange
        self.pair_list = set()

        if self.exhange == 'liqui':
            self.ob_constant = 30
            self.bl_constant = 60

        self.ccxt_it_queue = self.config['ccxt_in_queue']
        self.ccxt_out_queue = self.config['ccxt_out_queue']

        self.pair_list = self.config['pairs']

        # for i in self.config['pairs']:
        #     i['balance_tick'] = True
        #     self.pair_list.add( i['name'] )

        auth = {}
        if 'auth' in self.config.keys():
            auth = self.config['auth']
            self.is_auth = True
            self.name = '[ccxt %s %s*]' % (self.exhange, auth['apiKey'][:4])

        asyncio.set_event_loop(loop)

        if self.exhange == 'hitbtc':
            loop.create_task(self.run_loop(ccxt.hitbtc(auth)))
        elif self.exhange == 'coinmarketcap':
            loop.create_task(self.run_loop(ccxt.coinmarketcap()))
        elif self.exhange == 'binance':
            loop.create_task(self.run_loop(ccxt.binance(auth)))
        elif self.exhange == 'bitmex':
            loop.create_task(self.run_loop(ccxt.bitmex(auth)))
        elif self.exhange == 'huobipro':
            loop.create_task(self.run_loop(ccxt.huobipro()))
        elif self.exhange == 'liqui':
            loop.create_task(self.run_loop(ccxt.liqui(auth)))
        elif self.exhange == 'bitfinex2':
            loop.create_task(self.run_loop(ccxt.bitfinex2(auth)))
        elif self.exhange == 'bitfinex':
            loop.create_task(self.run_loop(ccxt.bitfinex(auth)))
        elif self.exhange == 'okex':
            loop.create_task(self.run_loop(ccxt.okex(auth)))
        elif self.exhange == 'kucoin':
            loop.create_task(self.run_loop(ccxt.kucoin(auth)))
        elif self.exhange == 'bittrex':
            loop.create_task(self.run_loop(ccxt.bittrex(auth)))
        elif self.exhange == 'qryptos':
            loop.create_task(self.run_loop(ccxt.qryptos(auth)))
        elif self.exhange == 'kraken':
            loop.create_task(self.run_loop(ccxt.kraken(auth)))

        loop.run_forever()
Esempio n. 43
0
    root.iconbitmap(iconfile)
    app = Application(master=root)
    app.mainloop()


##
## Shameless copy-paste & merge from
## https://stackoverflow.com/questions/17190221/subprocess-popen-cloning-stdout-and-stderr-both-to-terminal-and-variables/25960956#25960956
## https://stackoverflow.com/questions/16260061/reading-a-file-with-a-specified-delimiter-for-newline
## https://stackoverflow.com/questions/19600475/how-to-read-records-terminated-by-custom-separator-from-file-in-python
## For lack of a faster/cleaner solution.

# Run the event loop
if os.name == 'nt':
    loop = asyncio.ProactorEventLoop()  # for subprocess' pipes on Windows
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()


@asyncio.coroutine
def read_stream_and_display(stream, display):
    """Read from stream line by line (preserving format) until EOF, display, and capture the lines.
    """
    output = []
    buf = b''
    EOL_REGEX = b'\r\n|\r|\n'
    bufsize = 4096

    while True:
        newbuf = yield from stream.read(bufsize)
Esempio n. 44
0
 def setUp(self):
     self.stream = mock.Mock()
     self.transp = self.stream.transport
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(None)
Esempio n. 45
0
    def __init__(
        self,
        url: str,
        headers: Optional[HeadersLike] = None,
        ssl: Union[SSLContext, bool] = False,
        init_payload: Dict[str, Any] = {},
        connect_timeout: Optional[Union[int, float]] = 10,
        close_timeout: Optional[Union[int, float]] = 10,
        ack_timeout: Optional[Union[int, float]] = 10,
        keep_alive_timeout: Optional[Union[int, float]] = None,
        connect_args: Dict[str, Any] = {},
    ) -> None:
        """Initialize the transport with the given parameters.

        :param url: The GraphQL server URL. Example: 'wss://server.com:PORT/graphql'.
        :param headers: Dict of HTTP Headers.
        :param ssl: ssl_context of the connection. Use ssl=False to disable encryption
        :param init_payload: Dict of the payload sent in the connection_init message.
        :param connect_timeout: Timeout in seconds for the establishment
            of the websocket connection. If None is provided this will wait forever.
        :param close_timeout: Timeout in seconds for the close. If None is provided
            this will wait forever.
        :param ack_timeout: Timeout in seconds to wait for the connection_ack message
            from the server. If None is provided this will wait forever.
        :param keep_alive_timeout: Optional Timeout in seconds to receive
            a sign of liveness from the server.
        :param connect_args: Other parameters forwarded to websockets.connect
        """

        self.url: str = url
        self.headers: Optional[HeadersLike] = headers
        self.ssl: Union[SSLContext, bool] = ssl
        self.init_payload: Dict[str, Any] = init_payload

        self.connect_timeout: Optional[Union[int, float]] = connect_timeout
        self.close_timeout: Optional[Union[int, float]] = close_timeout
        self.ack_timeout: Optional[Union[int, float]] = ack_timeout
        self.keep_alive_timeout: Optional[Union[int,
                                                float]] = keep_alive_timeout

        self.connect_args = connect_args

        self.websocket: Optional[WebSocketClientProtocol] = None
        self.next_query_id: int = 1
        self.listeners: Dict[int, ListenerQueue] = {}

        self.receive_data_task: Optional[asyncio.Future] = None
        self.check_keep_alive_task: Optional[asyncio.Future] = None
        self.close_task: Optional[asyncio.Future] = None

        # We need to set an event loop here if there is none
        # Or else we will not be able to create an asyncio.Event()
        try:
            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore", message="There is no current event loop")
                self._loop = asyncio.get_event_loop()
        except RuntimeError:
            self._loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self._loop)

        self._wait_closed: asyncio.Event = asyncio.Event()
        self._wait_closed.set()

        self._no_more_listeners: asyncio.Event = asyncio.Event()
        self._no_more_listeners.set()

        if self.keep_alive_timeout is not None:
            self._next_keep_alive_message: asyncio.Event = asyncio.Event()
            self._next_keep_alive_message.set()

        self.payloads: Dict[str, Any] = {}
        """payloads is a dict which will contain the payloads received
        for example with the graphql-ws protocol: 'ping', 'pong', 'connection_ack'"""

        self._connecting: bool = False

        self.close_exception: Optional[Exception] = None

        # The list of supported subprotocols should be defined in the subclass
        self.supported_subprotocols: List[Subprotocol] = []

        self.response_headers: Optional[Headers] = None
def uper_status_coll2(uid):

    global uper_status_list

    asyncio.set_event_loop(asyncio.new_event_loop())
    loop = asyncio.get_event_loop()
    tasks = asyncio.gather(uper_spacenavnum_get(uid),
                           uper_relationstat_get(uid),
                           uper_spaceupstat_get(uid), uper_vipstatus_get(uid),
                           uper_elec_get(uid), uper_notice_get(uid))

    try:
        text_list = loop.run_until_complete(tasks)
    except NameError:
        print('too fast too fast')
        loop.close()
        time.sleep(60)
        uper_status_coll2(uid)
        return

    text_spacenavnum = text_list[0]
    jstext_spacenavnum = js.loads(text_spacenavnum, encoding='utf8')
    data_spacenavnum = jstext_spacenavnum['data']

    text_relationstat = text_list[1]
    jstext_relationstat = js.loads(text_relationstat, encoding='utf8')
    data_relationstat = jstext_relationstat['data']

    text_spaceupstat = text_list[2]
    jstext_spaceupstat = js.loads(text_spaceupstat, encoding='utf8')
    data_spaceupstat = jstext_spaceupstat['data']

    text_vipstatus = text_list[3]
    jstext_vipstatus = js.loads(text_vipstatus, encoding='utf8')
    data_vipstatus = jstext_vipstatus['data']

    text_elec = text_list[4]
    jstext_elec = js.loads(text_elec, encoding='utf8')

    text_notice = text_list[5]
    jstext_notice = js.loads(text_notice, encoding='utf8')

    loop.close()

    uid = uid
    mid_x = str(uid).zfill(12)
    video = data_spacenavnum['video']
    bangumi = data_spacenavnum['bangumi']
    channel_master = data_spacenavnum['channel']['master']
    channel_guest = data_spacenavnum['channel']['guest']
    favourite_master = data_spacenavnum['channel']['master']
    favourite_guest = data_spacenavnum['channel']['guest']
    tag = data_spacenavnum['tag']
    article = data_spacenavnum['article']
    playlist = data_spacenavnum['playlist']
    album = data_spacenavnum['album']

    following = data_relationstat['following']
    whisper = data_relationstat['whisper']
    black = data_relationstat['black']
    follower = data_relationstat['follower']

    try:
        archive_view = data_spaceupstat['archive']['view']
    except TypeError:
        archive_view = None
    try:
        article_view = data_spaceupstat['article']['view']
    except TypeError:
        article_view = None

    vipType = data_vipstatus['vipType']
    vipStatus = data_vipstatus['vipStatus']

    try:
        elec_count = jstext_elec['data']['count']
    except KeyError:
        elec_count = None
    try:
        elec_total_count = jstext_elec['data']['total_count']
    except KeyError:
        elec_total_count = None

    if jstext_notice['status'] == True:
        data_notice = jstext_notice['data']
        notice = data_notice['notice']
        try:
            notice_mtime = data_notice['modify_time']
        except KeyError:
            notice_mtime = None
    else:
        notice = None
        notice_mtime = None

    record_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    temp = [
        uid, mid_x, video, bangumi, channel_master, channel_guest,
        favourite_master, favourite_guest, tag, article, playlist, album,
        following, whisper, black, follower, archive_view, article_view,
        vipType, vipStatus, elec_count, elec_total_count, notice, notice_mtime,
        record_time
    ]

    uper_status_list.append(temp)
Esempio n. 47
0
 def thread(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.loop.run_until_complete(self.handler())
Esempio n. 48
0
 def __exit__(self, exc_type, exc_value, traceback):
     """Remove self from existing instances."""
     sys.path = self.stored_path
     self.__class__.instances = []
     asyncio.set_event_loop(asyncio.new_event_loop())
 def _t_bokeh_server(self):
     asyncio.set_event_loop(asyncio.new_event_loop())
     loop = tornado.ioloop.IOLoop.current()
     self._webapp.start(loop)
Esempio n. 50
0
 def start_webserver(self):
     # self.webserver_io_loop = asyncio.new_event_loop()
     if sys.version_info[0] > 2:
         import asyncio
         asyncio.set_event_loop(asyncio.new_event_loop())
     self.start_websocket_server()
    def _monitor(self):
        # set event loop in thread
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        super()._monitor()
Esempio n. 52
0
def getuser(user, plataforma):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    data = asyncio.get_event_loop().run_until_complete(main(user, plataforma))
    return data
Esempio n. 53
0
def worker(request, loop):
    asyncio.set_event_loop(loop)
    ret = request.param()
    ret.notify = mock.Mock()
    return ret
def function_event_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    return loop
Esempio n. 55
0
def thr():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
Esempio n. 56
0
 def qasync_init(self):
     app = QtWidgets.QApplication([])
     self.loop = QEventLoop(app)
     asyncio.set_event_loop(self.loop)
Esempio n. 57
0
def process(str):

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    result = loop.run_until_complete(inter(str))
    return result
Esempio n. 58
0
def loop_in_thread(loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(gather_hrs(loop))
def test_default_loop(loop):
    asyncio.set_event_loop(loop)
    req = ClientRequest('get', URL('http://python.org/'))
    assert req.loop is loop
Esempio n. 60
-1
    def test(self):
        """ Play PyChess-PyChess 1 min variant games """

        if sys.platform == "win32":
            from asyncio.windows_events import ProactorEventLoop
            loop = ProactorEventLoop()
            asyncio.set_event_loop(loop)
        else:
            loop = asyncio.SelectorEventLoop()
            asyncio.set_event_loop(loop)

        loop = asyncio.get_event_loop()
        loop.set_debug(enabled=True)

        for vari in PYCHESS_VARIANTS:
            variant = variants[vari]

            def coro():
                self.p0 = yield from discoverer.initEngine(self.engine, WHITE, False)
                self.p1 = yield from discoverer.initEngine(self.engine, BLACK, False)

            loop.run_until_complete(coro())

            def optionsCallback(engine):
                engine.setOptionVariant(variant)
                engine.setOptionStrength(1, False)
                engine.setOptionTime(60, 0, 0)

            self.p0.connect("readyForOptions", optionsCallback)
            self.p1.connect("readyForOptions", optionsCallback)

            def coro(variant):
                self.game = GameModel(TimeModel(60, 0), variant)
                self.game.setPlayers([self.p0, self.p1])

                def on_game_end(game, state, event):
                    event.set()

                event = asyncio.Event()
                self.game.connect("game_ended", on_game_end, event)

                self.p0.prestart()
                self.p1.prestart()

                if self.game.variant.need_initial_board:
                    for player in self.game.players:
                        player.setOptionInitialBoard(self.game)

                print(variant.name)
                self.game.start()

                yield from event.wait()

                pgn = StringIO()
                print(save(pgn, self.game))

                self.assertIsNone(self.p0.invalid_move)
                self.assertIsNone(self.p1.invalid_move)

            loop.run_until_complete(coro(variant))