Python threading.main_thread() Examples

The following are 30 code examples for showing how to use threading.main_thread(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module threading , or try the search function .

Example 1
Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
def cron_task_host():
    """定时任务宿主, 每分钟检查一次列表, 运行时间到了的定时任务"""
    while True:
        # 当全局开关关闭时, 自动退出线程
        if not enable_cron_tasks:
            if threading.current_thread() != threading.main_thread():
                exit()
            else:
                return

        sleep(60)
        try:
            task_scheduler.run()
        except:  # coverage: exclude
            errprint('ErrorDuringExecutingCronTasks')
            traceback.print_exc() 
Example 2
Project: dash-masternode-tool   Author: Bertrand256   File: psw_cache.py    License: MIT License 6 votes vote down vote up
def ask_for_password(username, host, message=None):
        if not SshPassCache.parent_window:
            raise Exception('SshPassCache not initialized')

        def query_psw(msg):
            password, ok = QInputDialog.getText(SshPassCache.parent_window, 'Password Dialog',
                                                msg, echo=QLineEdit.Password)
            return password, ok

        if not message:
            message = 'Enter password for ' + username + '@' + host + ':'

        if threading.current_thread() != threading.main_thread():
            password, ok = WndUtils.call_in_main_thread(query_psw, message)
        else:
            password, ok = query_psw(message)

        if not ok:
            raise CancelException
        return password 
Example 3
Project: dash-masternode-tool   Author: Bertrand256   File: wallet_dlg.py    License: MIT License 6 votes vote down vote up
def on_bip44_account_added(self, account: Bip44AccountType):
        """
        Called back from self.bip44_wallet after adding an item to the list of bip44 accounts. It is
        used in 'accounts view' mode for the subsequent display of read accounts.
        :param account: the account being added.
        """
        if not self.finishing:
            def fun():
                if self.utxo_src_mode == MAIN_VIEW_BIP44_ACCOUNTS:
                    self.account_list_model.add_account(account)

            log.debug('Adding account %s', account.id)
            if threading.current_thread() != threading.main_thread():
                if self.enable_synch_with_main_thread:
                    WndUtils.call_in_main_thread_ext(fun, skip_if_main_thread_locked=True)
            else:
                fun() 
Example 4
Project: dash-masternode-tool   Author: Bertrand256   File: wallet_dlg.py    License: MIT License 6 votes vote down vote up
def show_loading_tx_animation(self):
        if not self.wdg_loading_txs_animation:
            def show():
                size = min(self.wdgSpinner.height(), self.wdgSpinner.width())
                g = self.wdgSpinner.geometry()
                g.setWidth(size)
                g.setHeight(size)
                self.wdgSpinner.setGeometry(g)
                self.wdg_loading_txs_animation = SpinnerWidget(self.wdgSpinner, size, '', 11)
                self.wdg_loading_txs_animation.show()

            if threading.current_thread() != threading.main_thread():
                if self.enable_synch_with_main_thread:
                    WndUtils.call_in_main_thread_ext(show, skip_if_main_thread_locked=True)
            else:
                show() 
Example 5
Project: dash-masternode-tool   Author: Bertrand256   File: main_dlg.py    License: MIT License 6 votes vote down vote up
def update_edit_controls_state(self):
        def update_fun():
            editing = (self.editing_enabled and self.cur_masternode is not None)
            self.action_gen_mn_priv_key_uncompressed.setEnabled(editing)
            self.action_gen_mn_priv_key_compressed.setEnabled(editing)
            self.btnDeleteMn.setEnabled(self.cur_masternode is not None)
            self.btnEditMn.setEnabled(not self.editing_enabled and self.cur_masternode is not None)
            self.btnCancelEditingMn.setEnabled(self.editing_enabled and self.cur_masternode is not None)
            self.btnDuplicateMn.setEnabled(self.cur_masternode is not None)
            self.action_save_config_file.setEnabled(self.app_config.is_modified())
            self.action_disconnect_hw.setEnabled(True if self.hw_client else False)
            self.btnRefreshMnStatus.setEnabled(self.cur_masternode is not None)
            self.btnRegisterDmn.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_collateral_addr.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_owner_key.setEnabled(self.cur_masternode is not None)
            self.action_sign_message_with_voting_key.setEnabled(self.cur_masternode is not None)
            self.update_mn_controls_state()
        if threading.current_thread() != threading.main_thread():
            self.call_in_main_thread(update_fun)
        else:
            update_fun() 
Example 6
Project: dash-masternode-tool   Author: Bertrand256   File: wnd_utils.py    License: MIT License 6 votes vote down vote up
def queryDlg(message, buttons=QMessageBox.Ok | QMessageBox.Cancel, default_button=QMessageBox.Ok,
            icon=QMessageBox.Information):

        def dlg(message, buttons, default_button, icon):
            msg = QMessageBox()
            msg.setIcon(icon)
            msg.setTextInteractionFlags(
                Qt.TextSelectableByMouse | Qt.TextSelectableByKeyboard | Qt.LinksAccessibleByMouse)

            # because of the bug: https://bugreports.qt.io/browse/QTBUG-48964
            # we'll convert a message to HTML format to avoid bolded font on Mac platform
            if message.find('<html') < 0:
                message = '<html style="font-weight:normal">' + message.replace('\n', '<br>') + '</html>'

            msg.setText(message)
            msg.setStandardButtons(buttons)
            msg.setDefaultButton(default_button)
            return msg.exec_()

        if threading.current_thread() != threading.main_thread():
            return WndUtils.call_in_main_thread(dlg, message, buttons, default_button, icon)
        else:
            return dlg(message, buttons, default_button, icon) 
Example 7
Project: Fluid-Designer   Author: Microvellum   File: test_threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example 8
Project: Fluid-Designer   Author: Microvellum   File: test_threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example 9
Project: Fluid-Designer   Author: Microvellum   File: test_threading.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example 10
Project: ironpython3   Author: IronLanguages   File: test_threading.py    License: Apache License 2.0 6 votes vote down vote up
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example 11
Project: ironpython3   Author: IronLanguages   File: test_threading.py    License: Apache License 2.0 6 votes vote down vote up
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example 12
Project: ironpython3   Author: IronLanguages   File: test_threading.py    License: Apache License 2.0 6 votes vote down vote up
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example 13
Project: stackhut   Author: nstack   File: runner.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, backend, hutcfg):
        log.debug('Starting Service Runner')
        self.backend = backend
        self.hutcfg = hutcfg
        # select the stack
        self.shim_cmd = shim_cmds.get(self.hutcfg.stack)
        if self.shim_cmd is None:
            raise RuntimeError("Unknown stack - {}".format(self.hutcfg.stack))

        # init the local runtime service
        self.runtime_server = RuntimeServer(backend)
        # init the rpc server
        self.rpc = rpc.StackHutRPC(self.backend, self.shim_cmd)

        assert threading.current_thread() == threading.main_thread()
        signal.signal(signal.SIGTERM, sigterm_handler)
        signal.signal(signal.SIGINT, sigterm_handler) 
Example 14
Project: layered   Author: danijar   File: plot.py    License: MIT License 6 votes vote down vote up
def start(self, work):
        """
        Hand the main thread to the window and continue work in the provided
        function. A state is passed as the first argument that contains a
        `running` flag. The function is expected to exit if the flag becomes
        false. The flag can also be set to false to stop the window event loop
        and continue in the main thread after the `start()` call.
        """
        assert threading.current_thread() == threading.main_thread()
        assert not self.state.running
        self.state.running = True
        self.thread = threading.Thread(target=work, args=(self.state,))
        self.thread.start()
        while self.state.running:
            try:
                before = time.time()
                self.update()
                duration = time.time() - before
                plt.pause(max(0.001, self.refresh - duration))
            except KeyboardInterrupt:
                self.state.running = False
                self.thread.join()
                return 
Example 15
Project: sisyphus   Author: rwth-i6   File: tools.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def default_handle_exception_interrupt_main_thread(func):
    """
    :param func: any function. usually run in another thread.
      If some exception occurs, it will interrupt the main thread (send KeyboardInterrupt to the main thread).
      If this is run in the main thread itself, it will raise SystemExit(1).
    :return: function func wrapped
    """
    import sys
    import _thread
    import threading

    def wrapped_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception:
            logging.error("Exception in thread %r:" % threading.current_thread())
            sys.excepthook(*sys.exc_info())
            if threading.current_thread() is not threading.main_thread():
                _thread.interrupt_main()
            raise SystemExit(1)

    return wrapped_func 
Example 16
def test_main_thread_after_fork(self):
        code = """if 1:
            import os, threading

            pid = os.fork()
            if pid == 0:
                main = threading.main_thread()
                print(main.name)
                print(main.ident == threading.current_thread().ident)
                print(main.ident == threading.get_ident())
            else:
                os.waitpid(pid, 0)
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "MainThread\nTrue\nTrue\n") 
Example 17
def test_main_thread_after_fork_from_nonmain_thread(self):
        code = """if 1:
            import os, threading, sys

            def f():
                pid = os.fork()
                if pid == 0:
                    main = threading.main_thread()
                    print(main.name)
                    print(main.ident == threading.current_thread().ident)
                    print(main.ident == threading.get_ident())
                    # stdout is fully buffered because not a tty,
                    # we have to flush before exit.
                    sys.stdout.flush()
                else:
                    os.waitpid(pid, 0)

            th = threading.Thread(target=f)
            th.start()
            th.join()
        """
        _, out, err = assert_python_ok("-c", code)
        data = out.decode().replace('\r', '')
        self.assertEqual(err, b"")
        self.assertEqual(data, "Thread-1\nTrue\nTrue\n") 
Example 18
def test_3_join_in_forked_from_thread(self):
        # Like the test above, but fork() was called from a worker thread
        # In the forked process, the main Thread object must be marked as stopped.

        script = """if 1:
            main_thread = threading.current_thread()
            def worker():
                childpid = os.fork()
                if childpid != 0:
                    os.waitpid(childpid, 0)
                    sys.exit(0)

                t = threading.Thread(target=joiningfunc,
                                     args=(main_thread,))
                print('end of main')
                t.start()
                t.join() # Should not block: main_thread is already stopped

            w = threading.Thread(target=worker)
            w.start()
            """
        self._run_and_join(script) 
Example 19
def _init_gene_sets_finished(self, f):
        assert self.thread() is QThread.currentThread()
        assert threading.current_thread() == threading.main_thread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()

        self._task = None
        self.progress_bar.finish()
        self.setStatusMessage('')

        try:
            results = f.result()  # type: list
            [self.data_model.appendRow(model_item) for model_item in results]
            self.filter_proxy_model.setSourceModel(self.data_model)
            self.data_view.selectionModel().selectionChanged.connect(self.commit)
            self._update_fdr()
            self.filter_data_view()
            self.set_selection()
            self.update_info_box()

        except Exception as ex:
            print(ex) 
Example 20
Project: orange3-bioinformatics   Author: biolab   File: OWGeneSets.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _init_gene_sets_finished(self, f):
        assert self.thread() is QThread.currentThread()
        assert threading.current_thread() == threading.main_thread()
        assert self._task is not None
        assert self._task.future is f
        assert f.done()

        self._task = None
        self.progress_bar.finish()
        self.setStatusMessage('')

        try:
            results = f.result()  # type: list
            [self.data_model.appendRow(model_item) for model_item in results]
            self.filter_proxy_model.setSourceModel(self.data_model)
            self.data_view.selectionModel().selectionChanged.connect(self.commit)
            self.filter_data_view()
            self.set_selection()
            self.update_info_box()
        except Exception as ex:
            print(ex)
        self.setBlocking(False) 
Example 21
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: currentThread.py    License: MIT License 5 votes vote down vote up
def myChildThread():
  print("Child Thread Starting")
  time.sleep(5)
  print("Current Thread ----------")
  print(threading.current_thread())
  print("-------------------------")
  print("Main Thread -------------")
  print(threading.main_thread())
  print("-------------------------")
  print("Child Thread Ending") 
Example 22
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: mainThread.py    License: MIT License 5 votes vote down vote up
def myChildThread():
  print("Child Thread Starting")
  time.sleep(5)
  print("Current Thread ----------")
  print(threading.current_thread())
  print("-------------------------")
  print("Main Thread -------------")
  print(threading.main_thread())
  print("-------------------------")
  print("Child Thread Ending") 
Example 23
Project: dataflow   Author: tensorpack   File: concurrency.py    License: Apache License 2.0 5 votes vote down vote up
def is_main_thread():
    if six.PY2:
        return isinstance(threading.current_thread(), threading._MainThread)
    else:
        # a nicer solution with py3
        return threading.current_thread() == threading.main_thread() 
Example 24
Project: qutebrowser   Author: qutebrowser   File: crashsignal.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _handle_early_exits(self, exc):
        """Handle some special cases for the exception hook.

        Return value:
            True: Exception hook should be aborted.
            False: Continue handling exception.
        """
        exctype, _excvalue, tb = exc

        if not self._quitter.quit_status['crash']:
            log.misc.error("ARGH, there was an exception while the crash "
                           "dialog is already shown:", exc_info=exc)
            return True

        log.misc.error("Uncaught exception", exc_info=exc)

        is_ignored_exception = (exctype is bdb.BdbQuit or
                                not issubclass(exctype, Exception))

        if 'pdb-postmortem' in objects.debug_flags:
            if tb is None:
                pdb.set_trace()  # noqa: T100
            else:
                pdb.post_mortem(tb)

        if is_ignored_exception or 'pdb-postmortem' in objects.debug_flags:
            # pdb exit, KeyboardInterrupt, ...
            sys.exit(usertypes.Exit.exception)

        if threading.current_thread() != threading.main_thread():
            log.misc.error("Ignoring exception outside of main thread... "
                           "Please report this as a bug.")
            return True

        return False 
Example 25
Project: tox   Author: tox-dev   File: stdlib.py    License: MIT License 5 votes vote down vote up
def is_main_thread():
    """returns true if we are within the main thread"""
    cur_thread = threading.current_thread()
    if sys.version_info >= (3, 4):
        return cur_thread is threading.main_thread()
    else:
        # noinspection PyUnresolvedReferences
        return isinstance(cur_thread, threading._MainThread)


# noinspection PyPep8Naming 
Example 26
Project: moler   Author: nokia   File: connection_observer.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inside_main_thread():
        in_main_thread = threading.current_thread() is threading.main_thread()
        return in_main_thread 
Example 27
Project: BiblioPixel   Author: ManiacalLabs   File: animation_threading.py    License: MIT License 5 votes vote down vote up
def target(self):
        is_main = threading.current_thread() is threading.main_thread()
        log.debug('Animation starts on %s thread', 'main' if is_main else 'new')
        self.run()
        log.debug('Animation complete') 
Example 28
Project: python-slackclient   Author: slackapi   File: client.py    License: MIT License 5 votes vote down vote up
def start(self) -> asyncio.Future:
        """Starts an RTM Session with Slack.

        Makes an authenticated call to Slack's RTM API to retrieve
        a websocket URL and then connects to the message server.
        As events stream-in we run any associated callbacks stored
        on the client.

        If 'auto_reconnect' is specified we
        retrieve a new url and reconnect any time the connection
        is lost unintentionally or an exception is thrown.

        Raises:
            SlackApiError: Unable to retrieve RTM URL from Slack.
        """
        # TODO: Add Windows support for graceful shutdowns.
        if os.name != "nt" and current_thread() == main_thread():
            signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)
            for s in signals:
                self._event_loop.add_signal_handler(s, self.stop)

        future = asyncio.ensure_future(self._connect_and_read(), loop=self._event_loop)

        if self.run_async:
            return future
        return self._event_loop.run_until_complete(future) 
Example 29
Project: vpython-jupyter   Author: vpython   File: no_notebook.py    License: MIT License 5 votes vote down vote up
def onClose(self, wasClean, code, reason):
        """Called when browser tab is closed."""
        global websocketserving

        self.connection = None

        # We r done serving, let everyone else know...
        websocketserving = False

        # The cleanest way to get a fresh browser tab going in spyder
        # is to force vpython to be reimported each time the code is run.
        #
        # Even though this code is repeated in stop_server below we also
        # need it here because in spyder the script may have stopped on its
        # own ( because it has no infinite loop in it ) so the only signal
        # that the tab has been closed comes via the websocket.
        if _in_spyder:
            _undo_vpython_import_in_spyder()

        # We want to exit, but the main thread is running.
        # Only the main thread can properly call sys.exit, so have a signal
        # handler call it on the main thread's behalf.
        if platform.system() == 'Windows':
            if threading.main_thread().is_alive() and not _in_spyder:
                # On windows, if we get here then this signal won't be caught
                # by our signal handler. Just call it ourselves.
                os.kill(os.getpid(), signal.CTRL_C_EVENT)
            else:
                stop_server()
        else:
            os.kill(os.getpid(), signal.SIGINT) 
Example 30
Project: vpython-jupyter   Author: vpython   File: no_notebook.py    License: MIT License 5 votes vote down vote up
def stop_server():
    """Shuts down all threads and exits cleanly."""
    global __server
    __server.shutdown()
    event_loop = txaio.config.loop
    event_loop.stop()
    # We've told the event loop to stop, but it won't shut down until we poke
    # it with a simple scheduled task.
    event_loop.call_soon_threadsafe(lambda: None)

    # If we are in spyder, undo our import. This gets done in the websocket
    # server onClose above if the browser tab is closed but is not done
    # if the user stops the kernel instead.
    if _in_spyder:
        _undo_vpython_import_in_spyder()

    # We don't want Ctrl-C to try to sys.exit inside spyder, i.e.
    # in an ipython console with a separate python kernel running.
    if _in_spyder:
        raise KeyboardInterrupt

    if threading.main_thread().is_alive():
        sys.exit(0)
    else:
        pass
        # If the main thread has already stopped, the python interpreter
        # is likely just running .join on the two remaining threads (in
        # python/threading.py:_shutdown). Since we just stopped those threads,
        # we'll now exit.