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

Python multiprocessing.freeze_support函数代码示例

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

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



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

示例1: searchExecute

 def searchExecute(self):
     print 'searchExecute'
     input = self.input + self._testMethodName + ".csv"
     target = self.target + self._testMethodName
     cmd = "python ../src/jbmst.py " + input + " " + target
     freeze_support()
     p = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True)
     result = p.stdout.read()
     print result
     if result != "":
         self.rslt = result
         rsltList = result.split(',')
         if "," in result:
             self.rslt_number = rsltList[0].strip()
             self.rslt_filepath = self.getNormpath(rsltList[1].strip())
             self.rslt_hit = rsltList[2].strip()
             steps = rsltList[3].strip()
                  
             if(steps != ""):
                 if(steps == 1):
                     self.rslt_steps = [1]
                 else:
                     self.rslt_steps = steps.split(' ')
             else:
                 self.rslt_steps = None
开发者ID:TUBAME,项目名称:migration-tool,代码行数:25,代码来源:jbmst.py


示例2: startServer

def startServer():
    freeze_support()
    print('MagneticPendulum  -Cluster/Server')
    print('--------------------------------------------')
    print('Image resolution: {0}x{0} Output: {1}'.format(Parameter.RESOLUTION, Parameter.IMG_NAME))
    print('============================================')
    print('Now waiting to have some working clients.')
    import Simulation
    manager = ClusterQueueManager()
    data = []
    coordinates = manager.getCoordinates()
    values = manager.getValues()
    im= Image.new('RGB', (Parameter.RESOLUTION, Parameter.RESOLUTION))
    pixel = [] + [0]*(Parameter.RESOLUTION**2)
    Simulation.createAllCoordinates(coordinates, data)
    start = time.time()
    manager.start()
    while not coordinates.empty():
        while manager.getRunningClients() > 0:
            if not values.empty():
                Simulation.drawImage(im, data, pixel, values)
            time.sleep(Parameter.REPAINT)
        time.sleep(.5)
    print("Coordinates are now completely distributed.")
    
    while manager.getRunningClients() > 0:
        time.sleep(Parameter.REPAINT)
        print('Waiting for {0} clients to be done'.format(manager.getRunningClients()))
    Simulation.drawImage(im, data, pixel, values)
    print('Image succeeded. Time consumed: {0:.2f}s'.format((time.time() - start)))
    print('Exiting...')
    sys.exit(0)
开发者ID:Schille,项目名称:MagneticPendulum,代码行数:32,代码来源:ClusterServer.py


示例3: run

def run():
    """start GUI

    The function will create the main thread for Qt Gui. It will set the
    language to system locals an start an instance of the main window.
    """
    def install_translator(filename, folder, app):
        locale = QtCore.QLocale.system().name()
        translator = QtCore.QTranslator()
        if translator.load(filename.format(locale), folder):
            app.installTranslator(translator)
        return translator
    args = handle_cli_args()
    sys.excepthook = handle_exception
    multiprocessing.freeze_support()
    app = QtWidgets.QApplication(sys.argv)
    # set translation language
    folder = godirec.resource_filename("godirec", 'data/language')
    translator1 = install_translator("godirec_{}", folder, app)
    if hasattr(sys, "frozen"):
        qt_folder = godirec.resource_filename("godirec", "translations")
    else:
        qt_folder = QLibraryInfo.location(QLibraryInfo.TranslationsPath)
    translator2 = install_translator("qtbase_{}", qt_folder, app)
    window = main.GodiRecWindow()
    window.show()
    if "gdr_file" in args:
        window.setupProject(args["gdr_file"], False)
    else:
        audio.WaveConverter.confirm_converter_backend()
        if window.isNewProjectCreatedDialog():
            window.createNewProject()
    sys.exit(app.exec_())
开发者ID:quitejonny,项目名称:godirec,代码行数:33,代码来源:__init__.py


示例4: __call__

    def __call__(self, func, args=(), kwargs={}, timeout=1, default=None, raise_error=None):
        multiprocessing.freeze_support()

        if self.using_dill:
            payloads = dill.dumps((func, args, kwargs))
        else:
            payloads = func, args, kwargs

        queue       = multiprocessing.Queue()
        process     = multiprocessing.Process(target = self.__class__.container, args = (queue, payloads, self.using_dill))
        result      = default
        raise_error = raise_error if isinstance(raise_error, bool) else self.raise_error

        try:
            process.start()
            result = queue.get(block=True, timeout=timeout)
        except Empty:
            process.terminate()
            if hasattr(func, '__name__'):
                message = 'Method:{func_name}-{func_args}'.format(func_name=func.__name__, func_args=signature(func))
            else:
                message = 'Method:{func_obj}'.format(func_obj=func)
            result = TimeoutError('{message}, Timeout:{time}\'s'.format(message=message, time=timeout))
        finally:
            queue.close()
            process.join()
            if isinstance(result, Exception):
                if raise_error:
                    raise result  # pylint: disable=E0702
                return default
            return result
开发者ID:nawie,项目名称:python_tips,代码行数:31,代码来源:timeout.py


示例5: main

def main():
    """
    Entry point for GNS3 server
    """

    if sys.platform.startswith("win"):
        # necessary on Windows to use freezing software
        multiprocessing.freeze_support()

    current_year = datetime.date.today().year
    print("GNS3 server version {}".format(gns3server.__version__))
    print("Copyright (c) 2007-{} GNS3 Technologies Inc.".format(current_year))

    # we only support Python 2 version >= 2.7 and Python 3 version >= 3.3
    if sys.version_info < (2, 7):
        raise RuntimeError("Python 2.7 or higher is required")
    elif sys.version_info[0] == 3 and sys.version_info < (3, 3):
        raise RuntimeError("Python 3.3 or higher is required")

    try:
        tornado.options.parse_command_line()
    except (tornado.options.Error, ValueError):
        tornado.options.print_help()
        raise SystemExit

    # FIXME: log everything for now (excepting DEBUG)
    logging.basicConfig(level=logging.INFO)

    from tornado.options import options
    server = gns3server.Server(options.host,
                               options.port,
                               ipc=options.ipc)
    server.load_modules()
    server.run()
开发者ID:charlesnw1,项目名称:gns3-server,代码行数:34,代码来源:main.py


示例6: Main

def Main():
  """The main function."""
  multiprocessing.freeze_support()

  input_reader = cli_tools.StdinInputReader()
  tool = PsortTool(input_reader=input_reader)

  if not tool.ParseArguments():
    return False

  have_list_option = False
  if tool.list_analysis_plugins:
    tool.ListAnalysisPlugins()
    have_list_option = True

  if tool.list_output_modules:
    tool.ListOutputModules()
    have_list_option = True

  if tool.list_language_identifiers:
    tool.ListLanguageIdentifiers()
    have_list_option = True

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if have_list_option:
    return True

  tool.ProcessStorage()
  return True
开发者ID:alex8866,项目名称:plaso,代码行数:32,代码来源:psort.py


示例7: ServiceMain

	def ServiceMain(self):
		
		multiprocessing.freeze_support()
		win32api.SetConsoleCtrlHandler(self.ctrlHandler, True)
	
		parser=argparse.ArgumentParser(self._svc_display_name_, epilog=self.epilog, fromfile_prefix_chars="@")
		
		customInstallOptions=""
		for k,v in self.options.iteritems():
			customInstallOptions+=k[1:]+":"
			parser.add_argument(k, type=str, default=v.get("default", None),help=v.get("help", None))
		
		parser.add_argument("--username", type=str, default=None, help="User name")
		parser.add_argument("--password", type=str, default=None, help="Password")
		parser.add_argument("--startup", type=str, default="manual", help="Startup type (auto, manual, disabled)")
		
		subparsers=parser.add_subparsers(help="Subcommands")
		
		parserInstall=subparsers.add_parser("install", help="Install Service")
		
		parserUninstall=subparsers.add_parser("remove", help="Remove Service")
		
		parserConfig=subparsers.add_parser("update", help="Update Service")
		
		parserDebug=subparsers.add_parser("debug", help="Debug")
		
		parserStart=subparsers.add_parser("start", help="Start Service")
		
		parserStop=subparsers.add_parser("stop", help="Stop Service")
		
		parserRestart=subparsers.add_parser("restart", help="Restart Service")
		
		self.__name__=self.__class__.__name__
			
		win32serviceutil.HandleCommandLine(self,customInstallOptions=customInstallOptions, customOptionHandler=self.customOptionHandler)
开发者ID:rjungbeck,项目名称:rasterizer,代码行数:35,代码来源:servicebase.py


示例8: run

def run():
    freeze_support()
    global opMap

    

    if len(sys.argv) < 3:
        showHelp()
        return
    Pebble.hdfsRoot = sys.argv[1]
    opStr = sys.argv[2]
    sys.argv = sys.argv[3:]

    if not opMap.has_key(opStr):
        showHelp()
        return

    opInfo = opMap[opStr]

    #print len(sys.argv),sys.argv
    #print opInfo["argNum"] 
    if opInfo["argNum"] != len(sys.argv):
        showHelp(opStr)
        return

    startFunc = opInfo["startFunc"]
    startFunc()
开发者ID:LXiong,项目名称:rockstor,代码行数:27,代码来源:test.py


示例9: run

def run():
    argc = len(sys.argv)
    if argc != 4 and argc != 5:
        printUsage()
        return

    if argc == 4:
        sys.argv.append("0")

    [pyFile, op, srcDir, dstDir, num] = sys.argv

    try:
        num = long(num)
        freeze_support()
        if op == "file":
            mergeObjectFile(srcDir, dstDir, num)
        elif op == "result":
            mergeResult(srcDir, dstDir)
        else:
            print "merge type should be file or result!"
            printUsage()
            return
    except Exception, e:
        print e
        #printUsage()
        return
开发者ID:LXiong,项目名称:rockstor,代码行数:26,代码来源:mergeFile.py


示例10: action_distribute

def action_distribute(action, hosts, options):
    try:
        action = action.split('.')
        if len(action) != 2:
            raise ImportError
        model_name = action[0]
        func_name = action[1]
        # print(model_name, func_name, options)
        model_obj = __import__("module.%s" %model_name)
        model_obj = getattr(model_obj, model_name)
        func = getattr(model_obj, func_name)
        # print(model_obj, func)
        freeze_support()
        pool = Pool(conf.MULT_NUM) # 定义进程池子
        for host in hosts:
             pool.apply_async(func = func, args = (host ,options, ), callback = callback )
        pool.close()
        pool.join()
    except ImportError as e:
        error_msg = 'Module is not exit!'
        callback('error|%s' %error_msg)
        print(error_msg)
        exit(1)
    except AttributeError as e:
        error_msg = 'Function is not exit!'
        callback('error|%s' %error_msg)
        print(error_msg)
        exit(1)
开发者ID:ZhangXiaoyu-Chief,项目名称:OldBoy_Python,代码行数:28,代码来源:core.py


示例11: main

def main():
    freeze_support()

    logging.basicConfig(format='%(levelname)s, PID: %(process)d, %(asctime)s:\t%(message)s', level=logging.INFO)

    config = json.load(open('server_config.json'))

    orchestrator = Orchestrator(config)
    orchestrator.retrieve_file_data()
    orchestrator.init_server()
    orchestrator.server.generate_data()

    manager = multiprocessing.Manager()
    received_data = manager.dict()

    pp = ProcessParallel()

    pp.add_task(orchestrator.server.run, (received_data,))
    pp.add_task(orchestrator.send_data_to_server, ())

    pp.start_all()
    starts = time.time()

    pp.join_all()

    orchestrator.locate(received_data)

    ends = time.time()

    logging.info('%.15f passed for SEND/RECEIVE/CALCULATE.', ends - starts)

    orchestrator.get_results()
开发者ID:kn1m,项目名称:LocalizationTDOA,代码行数:32,代码来源:server_runner.py


示例12: MPRunner_actor

def MPRunner_actor(pipe,filename):
    multiprocessing.freeze_support()
    is_success = False
    old_stdin = sys.stdin
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    tmpfilename = tempfile.mktemp()+".n"
    res_std_out = u""
    old_exit = sys.exit
    sys.exit = lambda x: 0
    try:
        sys.stdout = codecs.open(tmpfilename,"w","utf-8")
        sys.stderr = sys.stdout
        executer = ezhil.EzhilFileExecuter(filename,debug=False,redirectop=False,TIMEOUT=3,encoding="utf-8",doprofile=False,safe_mode=True)
        executer.run()
        is_success = True
    except Exception as e:
        print(u" '{0}':\n{1}'".format(filename, unicode(e)))
    finally:
        print(u"######- நிரல் இயக்கி முடிந்தது-######")
        sys.exit = old_exit
        sys.stdout.flush()
        sys.stdout.close()
        with codecs.open(tmpfilename,u"r",u"utf-8") as fp:
            res_std_out = fp.read()
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        sys.stdin = old_stdin
    #print(pipe)
    #print("sending data back to source via pipe")
    pipe.send([ res_std_out,is_success] )
    pipe.close()
开发者ID:Ezhil-Language-Foundation,项目名称:Ezhil-Lang,代码行数:32,代码来源:iyakki.py


示例13: run_cli

def run_cli():
    from multiprocessing import freeze_support
    freeze_support()
    setup_logging()
    # Use default matplotlib backend on mac/linux, but wx on windows.
    # The problem on mac is that the wx backend requires pythonw.  On windows
    # we are sure to wx since it is the shipped with the app.
    setup_mpl(backend='WXAgg' if os.name == 'nt' else None)
    setup_sasmodels()
    if len(sys.argv) == 1 or sys.argv[1] == '-i':
        # Run sasview as an interactive python interpreter
        try:
            from IPython import start_ipython
            sys.argv = ["ipython", "--pylab"]
            sys.exit(start_ipython())
        except ImportError:
            import code
            code.interact(local={'exit': sys.exit})
    elif sys.argv[1] == '-c':
        exec(sys.argv[2])
    else:
        thing_to_run = sys.argv[1]
        sys.argv = sys.argv[1:]
        import runpy
        if os.path.exists(thing_to_run):
            runpy.run_path(thing_to_run, run_name="__main__")
        else:
            runpy.run_module(thing_to_run, run_name="__main__")
开发者ID:rprospero,项目名称:sasview,代码行数:28,代码来源:sasview.py


示例14: main

def main():
    """Entry point of the Bajoo client."""

    multiprocessing.freeze_support()

    # Start log and load config
    with log.Context():

        logger = logging.getLogger(__name__)
        cwd = to_unicode(os.getcwd(), in_enc=sys.getfilesystemencoding())
        logger.debug('Current working directory is : "%s"', cwd)

        config.load()  # config must be loaded before network
        log.set_debug_mode(config.get('debug_mode'))
        log.set_logs_level(config.get('log_levels'))

        # Set the lang from the config file if available
        lang = config.get('lang')
        if lang is not None:
            set_lang(lang)

        with network.Context():
            with encryption.Context():
                app = BajooApp()
                app.run()
开发者ID:Bajoo,项目名称:client-pc,代码行数:25,代码来源:__init__.py


示例15: loadWig

def loadWig(filename, smooth = True, strand = '+'):
    freeze_support()
    lines, count = readWigFile( filename )
    outQ = Queue()

    wig = {}
    print "loading wig --------------"

    NUM_PROCESSES = 3
    if not smooth:
        NUM_PROCESSES = 4
    processID = 1
    processes = []
    offset = 5

    for i in range( NUM_PROCESSES ):
        processes.append(Process( target = processChrom, args = ( lines, outQ, processID, offset, smooth, strand  ) ))
        processes[-1].start()
        processID += 1

    for i in range( count ):
        temp = outQ.get()
        print 'storing ', temp[0], ' ', type(temp[0]), ' ', temp[1].shape
        if temp[0] in wig:
            wig[temp[0]] = np.concatenate((wig[temp[0]], temp[1]), axis=0)
        else:
            wig[ temp[0] ] = temp[1]
    for i in range( NUM_PROCESSES ):
        lines.put( "STOP" )
    for i in range( NUM_PROCESSES ):
        processes[i].join()

    print 'Done loading ', filename
    return wig
开发者ID:hjanime,项目名称:CSI,代码行数:34,代码来源:wig.py


示例16: setup_and_run

def setup_and_run():
    # import only on run
    # Dont import always this, setup.py will fail
    from ninja_ide import core
    from multiprocessing import freeze_support
    #from PyQt4.QtCore import QDir
    import os
    #import shutil
    '''
    HOME_DIR = QDir.toNativeSeparators(QDir.homePath())
    if os.path.exists(os.path.join(HOME_DIR, '.alexa_ide')) is False:
        script_path = os.path.realpath(__file__)
        #script_path = os.path.abspath(__file__)
        script_path = os.path.dirname(script_path)
        #alexa_user_dir = QDir.toNativeSeparators("../")
        #alexa_user_dir = os.path.join(alexa_user_dir, script_path)
        alexa_user_filesdir = os.path.join(os.path.dirname(script_path), "user_files" + os.sep + "alexa_ide")
        #print alexa_user_filesdir
        shutil.copytree(alexa_user_filesdir, os.path.join(HOME_DIR, ".alexa_ide"))
    '''

    # Used to support multiprocessing on windows packages
    freeze_support()

    # Run NINJA-IDE
    core.run_ninja()
开发者ID:AlexaProjects,项目名称:Alexa2,代码行数:26,代码来源:__init__.py


示例17: run

 def run(self):
   if self.debug==False:
     freeze_support()
     Process(target=self.f).start()
   else:
     self.f()
     
开发者ID:python4d,项目名称:imd,代码行数:6,代码来源:MainApp.py


示例18: create_zoomtig

def create_zoomtig(out_dir, num_levels, images, PROCESSES):
    multiprocessing.freeze_support()
    #pool = multiprocessing.Pool(PROCESSES)
    for level in range(num_levels, -1, -1):
        
        
        tile_dir = out_dir + str(level) + "/"
        if not os.path.exists(tile_dir):
            os.mkdir(tile_dir)
        
        last_col = 0
        c = 0
        col_offsets = []
        
        last_col = 0
        for image_name in images:
            img = Image.open(image_name + ".png")
            image_width, image_height =  img.size
            num_cols =  int(math.ceil(float(image_width) / TILE_SIZE))
            col_offsets.append(last_col)
            last_col += num_cols
        TASKS = []
        for idx, image_name in enumerate(images):
            #TASKS.append((tile_image, (tile_dir, image_name, col_offsets[idx])))
            tile_image(tile_dir, image_name, col_offsets[idx])
        #pool.map_async(calculatestar, TASKS).get(9999999)
        #for idx, image_name in enumerate(images):
        #    tile_image(tile_dir, image_name, col_offsets[idx])
        resize_images(images)
        images = merge_images(images, out_dir)
开发者ID:vforget,项目名称:Contigo,代码行数:30,代码来源:zoomtig.py


示例19: test

def test():
	QueueManager.register('get_task_queue', callable=return_task_queue)
	QueueManager.register('get_result_queue', callable=return_result_queue)
	#绑定端口5000,设置验证码'abc'
	manager=QueueManager(address=('127.0.0.2',5007),authkey=b'abc')
	#启动Queue
	manager.start()
	#获得通过网络访问的queue对象:
	task=manager.get_task_queue()
	result=manager.get_result_queue()
	#放几个任务进去
	for i in range(10):
		n=random.randint(0,10000)
		print('Put task %d...' % n)
		task.put(n)
	#从result对读取结果
	print('Try get results...')
	for i in range(10):
	r=result.get(timeout=10)
	print('Result: %s' % r )
	#关闭
	manager.shutdown()
	print('master exit.')
if __name__='__main__':
	freeze_support()
	test()
开发者ID:BooYang-CS,项目名称:python3_code,代码行数:26,代码来源:task_master.py


示例20: main

def main():
    if iswindows:
        if '--multiprocessing-fork' in sys.argv:
            # We are using the multiprocessing module on windows to launch a
            # worker process
            from multiprocessing import freeze_support
            freeze_support()
            return 0
        # Close open file descriptors inherited from parent
        # On Unix this is done by the subprocess module
        os.closerange(3, 256)
    if isosx and 'CALIBRE_WORKER_ADDRESS' not in os.environ and 'CALIBRE_SIMPLE_WORKER' not in os.environ and '--pipe-worker' not in sys.argv:
        # On some OS X computers launchd apparently tries to
        # launch the last run process from the bundle
        # so launch the gui as usual
        from calibre.gui2.main import main as gui_main
        return gui_main(['calibre'])
    csw = os.environ.get('CALIBRE_SIMPLE_WORKER', None)
    if csw:
        mod, _, func = csw.partition(':')
        mod = importlib.import_module(mod)
        func = getattr(mod, func)
        func()
        return
    if '--pipe-worker' in sys.argv:
        try:
            exec (sys.argv[-1])
        except Exception:
            print('Failed to run pipe worker with command:', sys.argv[-1])
            raise
        return
    address = cPickle.loads(unhexlify(os.environ['CALIBRE_WORKER_ADDRESS']))
    key     = unhexlify(os.environ['CALIBRE_WORKER_KEY'])
    resultf = unhexlify(os.environ['CALIBRE_WORKER_RESULT']).decode('utf-8')
    with closing(Client(address, authkey=key)) as conn:
        name, args, kwargs, desc = eintr_retry_call(conn.recv)
        if desc:
            prints(desc)
            sys.stdout.flush()
        func, notification = get_func(name)
        notifier = Progress(conn)
        if notification:
            kwargs[notification] = notifier
            notifier.start()

        result = func(*args, **kwargs)
        if result is not None and os.path.exists(os.path.dirname(resultf)):
            cPickle.dump(result, open(resultf, 'wb'), -1)

        notifier.queue.put(None)

    try:
        sys.stdout.flush()
    except EnvironmentError:
        pass  # Happens sometimes on OS X for GUI processes (EPIPE)
    try:
        sys.stderr.flush()
    except EnvironmentError:
        pass  # Happens sometimes on OS X for GUI processes (EPIPE)
    return 0
开发者ID:artbycrunk,项目名称:calibre,代码行数:60,代码来源:worker.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python multiprocessing.get_context函数代码示例发布时间:2022-05-27
下一篇:
Python multiprocessing.current_process函数代码示例发布时间: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