• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python process.current_process函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中multiprocessing.process.current_process函数的典型用法代码示例。如果您正苦于以下问题:Python current_process函数的具体用法?Python current_process怎么用?Python current_process使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了current_process函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_temp_dir

def get_temp_dir():
    # get name of a temp directory which will be automatically cleaned up
    if current_process()._tempdir is None:
        import shutil, tempfile
        tempdir = tempfile.mkdtemp(prefix='pymp-')
        info('created temp directory %s', tempdir)
        Finalize(None, shutil.rmtree, args=[tempdir], exitpriority=-100)
        current_process()._tempdir = tempdir
    return current_process()._tempdir
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:9,代码来源:util.py


示例2: worker

def worker(worker_queue, result_queue):
    try:
        for number in iter(worker_queue.get, None):
            print number
            Crawl.crawl_web(number)
            result_queue.put("%s success with: %s" % (number,
                                                      current_process().name))
    except Exception, e:
        result_queue.put("%s failed with: %s" % (current_process().name,
                                                       e.message))
开发者ID:geekman2,项目名称:Parallel-Crawl,代码行数:10,代码来源:Parellel2.py


示例3: run

    def run(self):
        import time

        print "self.arr[10] = %f, Process = %s" % (self.arr[10], current_process())

        print self.arr.shape

        n = self.arr.shape[0] - 1

        print "self.arr[%d] = %f, Process = %s" % (n, self.arr[n], current_process())
        time.sleep(10)
开发者ID:khaikhai,项目名称:kineticsTools,代码行数:11,代码来源:testShared.py


示例4: prepare

def prepare(data):
    """
    Try to get current process ready to unpickle process object
    """
    old_main_modules.append(sys.modules['__main__'])
    if 'name' in data:
        process.current_process().name = data['name']
    if 'authkey' in data:
        process.current_process()._authkey = data['authkey']
    if 'log_to_stderr' in data and data['log_to_stderr']:
        util.log_to_stderr()
    if 'log_level' in data:
        util.get_logger().setLevel(data['log_level'])
    if 'sys_path' in data:
        sys.path = data['sys_path']
    if 'sys_argv' in data:
        sys.argv = data['sys_argv']
    if 'dir' in data:
        os.chdir(data['dir'])
    if 'orig_dir' in data:
        process.ORIGINAL_DIR = data['orig_dir']
    if 'main_path' in data:
        main_path = data['main_path']
        main_name = os.path.splitext(os.path.basename(main_path))[0]
        main_name = main_name == '__init__' and os.path.basename(os.path.dirname(main_path))
    if main_name != 'ipython':
        import imp
        if main_path is None:
            dirs = None
        elif os.path.basename(main_path).startswith('__init__.py'):
            dirs = [os.path.dirname(os.path.dirname(main_path))]
        else:
            dirs = [os.path.dirname(main_path)]
        if not main_name not in sys.modules:
            raise AssertionError(main_name)
            file, path_name, etc = imp.find_module(main_name, dirs)
            try:
                main_module = imp.load_module('__parents_main__', file, path_name, etc)
            finally:
                if file:
                    file.close()

            sys.modules['__main__'] = main_module
            main_module.__name__ = '__main__'
            for obj in main_module.__dict__.values():
                try:
                    if obj.__module__ == '__parents_main__':
                        obj.__module__ = '__main__'
                except Exception:
                    pass

    return
开发者ID:webiumsk,项目名称:WOT-0.9.12,代码行数:52,代码来源:forking.py


示例5: makeRecord

 def makeRecord(self, *args, **kwds):
     record = OldLoggerClass.makeRecord(self, *args, **kwds)
     if current_process:
         record.processName = current_process()._name
     else:
         record.processName = ""
     return record
开发者ID:Aaron1011,项目名称:oh-mainline,代码行数:7,代码来源:patch.py


示例6: imply_start

    def imply_start(self):
        _aspect = cs_aspect(self.sub)

        tracker = self.state_persist.start_aspect(_aspect)
        if tracker:
            self.state_persist.set_state_data(_aspect, {"state": "started", "by": current_process().pid})
            return tracker
开发者ID:AlexeyProskuryakov,项目名称:read,代码行数:7,代码来源:reader.py


示例7: main

 def main():
     """
     Run code specified by data received over pipe
     """
     raise is_forking(sys.argv) or AssertionError
     handle = int(sys.argv[-1])
     fd = msvcrt.open_osfhandle(handle, os.O_RDONLY)
     from_parent = os.fdopen(fd, 'rb')
     process.current_process()._inheriting = True
     preparation_data = load(from_parent)
     prepare(preparation_data)
     self = load(from_parent)
     process.current_process()._inheriting = False
     from_parent.close()
     exitcode = self._bootstrap()
     exit(exitcode)
开发者ID:webiumsk,项目名称:WOT-0.9.12,代码行数:16,代码来源:forking.py


示例8: _exit_function

def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers,
                   active_children=active_children,
                   current_process=current_process):
    # NB: we hold on to references to functions in the arglist due to the
    # situation described below, where this function is called after this
    # module's globals are destroyed.

    global _exiting

    info('process shutting down')
    debug('running all "atexit" finalizers with priority >= 0')
    _run_finalizers(0)

    if current_process() is not None:
        # NB: we check if the current process is None here because if
        # it's None, any call to ``active_children()`` will throw an
        # AttributeError (active_children winds up trying to get
        # attributes from util._current_process).  This happens in a
        # variety of shutdown circumstances that are not well-understood
        # because module-scope variables are not apparently supposed to
        # be destroyed until after this function is called.  However,
        # they are indeed destroyed before this function is called.  See
        # issues 9775 and 15881.  Also related: 4106, 9205, and 9207.

        for p in active_children():
            if p._daemonic:
                info('calling terminate() for daemon %s', p.name)
                p._popen.terminate()

        for p in active_children():
            info('calling join() for process %s', p.name)
            p.join()

    debug('running the remaining "atexit" finalizers')
    _run_finalizers()
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:35,代码来源:util.py


示例9: get_preparation_data

def get_preparation_data(name):
    '''
    Return info about parent needed by child to unpickle process object.
    Monkey-patch from
    
    http://www.velocityreviews.com/forums/t669125-using-multiprocessing-from-a-windows-service.html
    '''
    d = dict(
        name=name,
        sys_path=sys.path,
        sys_argv=sys.argv,
        log_to_stderr=_log_to_stderr,
        orig_dir=process.ORIGINAL_DIR,
        authkey=process.current_process().authkey,
    )
    
    if _logger is not None:
        d['log_level'] = _logger.getEffectiveLevel()
    
    if not WINEXE:
        main_path = getattr(sys.modules['__main__'], '__file__', None)
        if not main_path and sys.argv[0] not in ('', '-c'):
            main_path = sys.argv[0]
        if main_path is not None:
            if not os.path.isabs(main_path) and process.ORIGINAL_DIR\
                 is not None:
                main_path = os.path.join(process.ORIGINAL_DIR,main_path)
            if not main_path.endswith('.exe'):
                d['main_path'] = os.path.normpath(main_path)
                
    return d
开发者ID:cyberj,项目名称:pulsar,代码行数:31,代码来源:winprocess.py


示例10: get_command_line

    def get_command_line():
        '''
        Returns prefix of command line used for spawning a child process
        '''
        if getattr(process.current_process(), '_inheriting', False):
            raise RuntimeError('''
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.

            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:

                if __name__ == '__main__':
                    freeze_support()
                    ...

            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable.''')

        if getattr(sys, 'frozen', False):
            return [sys.executable, '--multiprocessing-fork']
        else:
            prog = 'from multiprocessing.forking import main; main()'
            opts = util._args_from_interpreter_flags()
            return [_python_exe] + opts + ['-c', prog, '--multiprocessing-fork']
开发者ID:timm,项目名称:timmnix,代码行数:25,代码来源:forking.py


示例11: launch

    def launch(self, proc_number):
        """Runs a simulation
        :return: double: the ratio of successful hands over total hands
        """

        logging.info(process.current_process().name + ': Plot data will be collected every {} runs'.
                     format(self.collect_frequency))

        success_count = 0
        deck = Deck()

        for sim_nb in range(self.number_simulations):
            deck.initialise()
            card_rules=CardRules(deck)
            card_rules.set_target(self.target_rank)

            cards_in_hand = self.get_starting_hand(deck, self.starting_cards)

            for v in range(self.number_of_draws):
                retained_cards = card_rules.apply_rules(cards_in_hand)
                #draw additional cards from deck to make a full hand
                dealer_cards = [deck.get_card() for c in
                                range(self.MAX_CARDS_IN_HAND - len(retained_cards))]
                cards_in_hand=retained_cards+dealer_cards

            # at the end of the last draw we check the final hand to see if we hit the target
            is_success=card_rules.check_success(cards_in_hand)
            if is_success:
                success_count += 1
            if self.is_plot and sim_nb % self.collect_frequency == 0 and sim_nb > 0:
                self._intermediate_results.append((success_count) / sim_nb)

        self._simulation_result = (success_count)/self.number_simulations
        return self
开发者ID:jule64,项目名称:TripleDraw,代码行数:34,代码来源:simulation.py


示例12: get_command_line

    def get_command_line():
        """
        Returns prefix of command line used for spawning a child process
        """
        if getattr(process.current_process(), "_inheriting", False):
            raise RuntimeError(
                """
            Attempt to start a new process before the current process
            has finished its bootstrapping phase.

            This probably means that you are on Windows and you have
            forgotten to use the proper idiom in the main module:

                if __name__ == '__main__':
                    freeze_support()
                    ...

            The "freeze_support()" line can be omitted if the program
            is not going to be frozen to produce a Windows executable."""
            )

        if getattr(sys, "frozen", False):
            return [sys.executable, "--multiprocessing-fork"]
        else:
            prog = "from multiprocessing.forking import main; main()"
            return [_python_exe, "-c", prog, "--multiprocessing-fork"]
开发者ID:bpgriner01,项目名称:psycopg2-windows,代码行数:26,代码来源:forking.py


示例13: get_preparation_data

    def get_preparation_data(name):
        '''
        Return info about parent needed by child to unpickle process object
        '''
        from .util import _logger, _log_to_stderr

        d = dict(
            name=name,
            sys_path=sys.path,
            sys_argv=sys.argv,
            log_to_stderr=_log_to_stderr,
            orig_dir=process.ORIGINAL_DIR,
            authkey=process.current_process().authkey,
            )

        if _logger is not None:
            d['log_level'] = _logger.getEffectiveLevel()

        if not WINEXE and not WINSERVICE:
            main_path = getattr(sys.modules['__main__'], '__file__', None)
            if not main_path and sys.argv[0] not in ('', '-c'):
                main_path = sys.argv[0]
            if main_path is not None:
                if not os.path.isabs(main_path) and \
                                          process.ORIGINAL_DIR is not None:
                    main_path = os.path.join(process.ORIGINAL_DIR, main_path)
                d['main_path'] = os.path.normpath(main_path)

        return d
开发者ID:timm,项目名称:timmnix,代码行数:29,代码来源:forking.py


示例14: get_preparation_data

def get_preparation_data(name):
    """
    Return info about parent needed by child to unpickle process object.
    Monkey-patch from
    """
    d = dict(
        name=name,
        sys_path=sys.path,
        sys_argv=sys.argv,
        log_to_stderr=_log_to_stderr,
        orig_dir=process.ORIGINAL_DIR,
        authkey=process.current_process().authkey,
    )

    if _logger is not None:
        d["log_level"] = _logger.getEffectiveLevel()

    if not WINEXE:
        main_path = getattr(sys.modules["__main__"], "__file__", None)
        if not main_path and sys.argv[0] not in ("", "-c"):
            main_path = sys.argv[0]
        if main_path is not None:
            if not os.path.isabs(main_path) and process.ORIGINAL_DIR is not None:
                main_path = os.path.join(process.ORIGINAL_DIR, main_path)
            if not main_path.endswith(".exe"):
                d["main_path"] = os.path.normpath(main_path)

    return d
开发者ID:Danzeer,项目名称:pulsar,代码行数:28,代码来源:winprocess.py


示例15: get_preparation_data

def get_preparation_data(name, init_main_module=True):
    '''
    Return info about parent needed by child to unpickle process object
    '''
    _check_not_importing_main()
    d = dict(
        log_to_stderr=util._log_to_stderr,
        authkey=bytes(process.current_process().authkey),
    )

    if util._logger is not None:
        d['log_level'] = util._logger.getEffectiveLevel()
        if len(util._logger.handlers) > 0:
            h = util._logger.handlers[0]
            d['log_fmt'] = h.formatter._fmt

    sys_path = [p for p in sys.path]
    try:
        i = sys_path.index('')
    except ValueError:
        pass
    else:
        sys_path[i] = process.ORIGINAL_DIR

    d.update(
        name=name,
        sys_path=sys_path,
        sys_argv=sys.argv,
        orig_dir=process.ORIGINAL_DIR,
        dir=os.getcwd()
    )

    if sys.platform != "win32":
        # Pass the semaphore_tracker pid to avoid re-spawning it in every child
        from . import semaphore_tracker
        semaphore_tracker.ensure_running()
        d['tracker_pid'] = semaphore_tracker._semaphore_tracker._pid

    # Figure out whether to initialise main in the subprocess as a module
    # or through direct execution (or to leave it alone entirely)
    if init_main_module:
        main_module = sys.modules['__main__']
        try:
            main_mod_name = getattr(main_module.__spec__, "name", None)
        except BaseException:
            main_mod_name = None
        if main_mod_name is not None:
            d['init_main_from_name'] = main_mod_name
        elif sys.platform != 'win32' or (not WINEXE and not WINSERVICE):
            main_path = getattr(main_module, '__file__', None)
            if main_path is not None:
                if (not os.path.isabs(main_path) and
                        process.ORIGINAL_DIR is not None):
                    main_path = os.path.join(process.ORIGINAL_DIR, main_path)
                d['init_main_from_path'] = os.path.normpath(main_path)
                # Compat for python2.7
                d['main_path'] = d['init_main_from_path']

    return d
开发者ID:MartinThoma,项目名称:scikit-learn,代码行数:59,代码来源:spawn.py


示例16: prepare

def prepare(data):
    '''
    Try to get current process ready to unpickle process object
    '''
    if 'name' in data:
        process.current_process().name = data['name']

    if 'authkey' in data:
        process.current_process().authkey = data['authkey']

    if 'log_to_stderr' in data and data['log_to_stderr']:
        util.log_to_stderr()

    if 'log_level' in data:
        util.get_logger().setLevel(data['log_level'])

    if 'log_fmt' in data:
        import logging
        util.get_logger().handlers[0].setFormatter(
            logging.Formatter(data['log_fmt'])
        )

    if 'sys_path' in data:
        sys.path = data['sys_path']

    if 'sys_argv' in data:
        sys.argv = data['sys_argv']

    if 'dir' in data:
        os.chdir(data['dir'])

    if 'orig_dir' in data:
        process.ORIGINAL_DIR = data['orig_dir']

    if hasattr(mp, 'set_start_method'):
        mp.set_start_method('loky', force=True)

    if 'tacker_pid' in data:
        from . import semaphore_tracker
        semaphore_tracker._semaphore_tracker._pid = data["tracker_pid"]

    if 'init_main_from_name' in data:
        _fixup_main_from_name(data['init_main_from_name'])
    elif 'init_main_from_path' in data:
        _fixup_main_from_path(data['init_main_from_path'])
开发者ID:as133,项目名称:scikit-learn,代码行数:45,代码来源:spawn.py


示例17: set_mp_process_title

def set_mp_process_title(progname, info=None):
    """Set the ps name using the multiprocessing process name.

    Only works if :mod:`setproctitle` is installed.

    """
    from multiprocessing.process import current_process
    return set_process_title("%s.%s" % (progname, current_process().name),
                             info=info)
开发者ID:HonzaKral,项目名称:celery,代码行数:9,代码来源:platform.py


示例18: sim_mask

def sim_mask(args):
    # Properly Parallel
    # http://stackoverflow.com/questions/444591/convert-a-string-of-bytes-into-an-int-python
    myid = current_process()._identity[0]
    np.random.seed(myid ^ struct.unpack("<L", os.urandom(4))[0])

    # Be Nice
    niceness = os.nice(0)
    os.nice(5 - niceness)

    lives = 10
    kwargs, pp_defaults, retain_data = args
    sim_time = kwargs.pop("sim_time", None)
    while True:
        try:
            sim = Simulation(**kwargs)
            logging.info("{0} starting {1}".format(current_process(), sim.title))
            prep_stats = sim.prepare(sim_time=sim_time)
            sim_time = sim.simulate()
            return_dict = sim.postprocess(**pp_defaults)
            if retain_data is True:  # Implicitly implies boolean datatype
                return_val = sim.generate_datapackage()
            elif retain_data == "additional_only":
                dp = sim.generate_datapackage()
                return_val = dp.additional.copy()
            elif retain_data == "file":
                return_val = sim.generate_datapackage().write(
                    kwargs.get("title"))
            else:
                return_val = return_dict
            del sim
            return return_val
        except (KeyboardInterrupt, SystemExit):
            raise
        except RuntimeError:
            lives -= 1
            if lives <= 0:
                raise
            else:
                logging.critical(
                    "{0} died, restarting: {1} lives remain".format(current_process(), lives))
                del sim
        gc.collect()
开发者ID:andrewbolster,项目名称:aietes,代码行数:43,代码来源:Threaded.py


示例19: _getPool

 def _getPool(self):
     '''
     Provides the pool for the current process.
     '''
     process = current_process()
     try: return process._ally_db_pool
     except AttributeError: pass
     pool = process._ally_db_pool = self._wrapped.recreate()
     self._pools.add(pool)
     return pool
开发者ID:AtomLaw,项目名称:Ally-Py,代码行数:10,代码来源:pool.py


示例20: set_mp_process_title

def set_mp_process_title(progname, info=None, hostname=None):
    """Set the ps name using the multiprocessing process name.

    Only works if :mod:`setproctitle` is installed.

    """
    from multiprocessing.process import current_process
    if hostname:
        progname = "%[email protected]%s" % (progname, hostname.split(".")[0])
    return set_process_title("%s:%s" % (progname, current_process().name),
                             info=info)
开发者ID:aleszoulek,项目名称:celery,代码行数:11,代码来源:platforms.py



注:本文中的multiprocessing.process.current_process函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python process.Process类代码示例发布时间:2022-05-27
下一篇:
Python pool.ThreadPool类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap