当前位置: 首页>>代码示例>>Python>>正文


Python Process.terminate方法代码示例

本文整理汇总了Python中multiprocessing.Process.terminate方法的典型用法代码示例。如果您正苦于以下问题:Python Process.terminate方法的具体用法?Python Process.terminate怎么用?Python Process.terminate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在multiprocessing.Process的用法示例。


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

示例1: SocketServer

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
class SocketServer(asyncore.dispatcher):
	def __init__(self, host, port):
		self.clients = Clients()
		asyncore.dispatcher.__init__(self)
		self.port = port
		self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
		self.set_reuse_addr()
		self.bind((host, port))
		self.bind = host
		self.listen(5)

	def __sock_process(self, socket):
		self.clients.append(socket)
		self.socketHandler = SocketHandler(self, socket)

	#handle when a connection is established and a connect() has been issued, add client
	def handle_accept(self):
		pair = self.accept()
		if pair != None:
			socket, addr = pair
			self.s = Process(target=self.__sock_process(socket), args=[])

			try:
				self.s.start()
			except:
				self.s.terminate()

	#handle when connection is closed and remove client
	def handle_close(self):
		self.clients.remove_all()
		self.s.close()
		print 'Sockets closed'
开发者ID:syurchi,项目名称:mobile-gamepad-control,代码行数:34,代码来源:socketServer.py

示例2: run_parkinglot_expt

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
def run_parkinglot_expt(net, n):
    "Run experiment"

    seconds = args.time

    # Start the bandwidth and cwnd monitors in the background
    monitor = Process(target=monitor_devs_ng,
            args=('%s/bwm.txt' % args.dir, 1.0))
    monitor.start()
    start_tcpprobe()

    # Get receiver and clients
    recvr = net.getNodeByName('receiver')
    sender1 = net.getNodeByName('h1')

    # Start the receiver
    port = 5001
    recvr.cmd('iperf -s -p', port,
              '> %s/iperf_server.txt' % args.dir, '&')

    waitListening(sender1, recvr, port)

    # TODO: start the sender iperf processes and wait for the flows to finish
    # Hint: Use getNodeByName() to get a handle on each sender.
    # Hint: Use sendCmd() and waitOutput() to start iperf and wait for them to finish
    # Hint: waitOutput waits for the command to finish allowing you to wait on a particular process on the host
    # iperf command to start flow: 'iperf -c %s -p %s -t %d -i 1 -yc > %s/iperf_%s.txt' % (recvr.IP(), 5001, seconds, args.dir, node_name)
    # Hint (not important): You may use progress(t) to track your experiment progress

    recvr.cmd('kill %iperf')

    # Shut down monitors
    monitor.terminate()
    stop_tcpprobe()
开发者ID:09beeihaq,项目名称:gt-cs6250,代码行数:36,代码来源:parkinglot.py

示例3: KeepAliveClientTest

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
class KeepAliveClientTest(TestCase):

    server_address = ("127.0.0.1", 65535)

    def __init__(self, *args, **kwargs):
        super(KeepAliveClientTest, self).__init__(*args, **kwargs)
        self.server_process = Process(target=self._run_server)

    def setUp(self):
        super(KeepAliveClientTest, self).setUp()
        self.client = Client(["%s:%d" % self.server_address])
        self.server_process.start()
        time.sleep(.10)

    def tearDown(self):
        self.server_process.terminate()
        super(KeepAliveClientTest, self).tearDown()

    def _run_server(self):
        self.server = BaseHTTPServer.HTTPServer(self.server_address, ClientAddressRequestHandler)
        self.server.handle_request()

    def test_client_keepalive(self):
        for x in range(10):
            result = self.client.sql("select * from fake")

            another_result = self.client.sql("select again from fake")
            self.assertEqual(result, another_result)
开发者ID:mike-schiller,项目名称:crate-python,代码行数:30,代码来源:test_http.py

示例4: start_schedulers

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
def start_schedulers(options):
    apps = [app.strip() for app in options.scheduler.split(',')]
    try:
        from multiprocessing import Process
    except:
        sys.stderr.write('Sorry, -K only supported for python 2.6-2.7\n')
        return
    processes = []
    code = "from gluon import current;current._scheduler.loop()"
    for app in apps:
        if not check_existent_app(options, app):
            print "Application '%s' doesn't exist, skipping" % (app)
            continue
        print 'starting scheduler for "%s"...' % app
        args = (app,True,True,None,False,code)
        logging.getLogger().setLevel(options.debuglevel)
        p = Process(target=run, args=args)
        processes.append(p)
        print "Currently running %s scheduler processes" % (len(processes))
        p.start()
        print "Processes started"
    for p in processes:
        try:
            p.join()
        except (KeyboardInterrupt, SystemExit):
            print "Processes stopped"
        except:
            p.terminate()
            p.join()
开发者ID:faridsanusi,项目名称:web2py,代码行数:31,代码来源:widget.py

示例5: test

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
    def test():

        queue = Queue()

        proc = Process(target=doNothing, args=(queue, ))
        proc.start()

        _logger.info("Started dummy process with PID %d", proc.pid)
        startCodeCheckerServerAttachedToPid(proc.pid)
        time.sleep(3)
        _logger.info("Allowing the dummy process to finish")
        queue.put(1)
        proc.join()

        if utils.isProcessRunning(proc.pid):
            _logger.warning("Dummy process %d was still running", proc.pid)
            proc.terminate()
            time.sleep(1)
            it.assertFalse(utils.isProcessRunning(proc.pid),
                           "Process %d is still running after terminating "
                           "it!" % proc.pid)

        time.sleep(1)
        _logger.info("Server should have died by now")

        with it.assertRaises(requests.ConnectionError):
            requests.post(it._url + '/get_diagnose_info')
开发者ID:suoto,项目名称:hdlcc,代码行数:29,代码来源:test_hdlcc_server.py

示例6: __init__

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
class msListener:

    def __init__(self, location, rules):
        self.rules = rules
        self.location = location
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.bind(location)
        self.sock.listen(5)  # backlog, queued connections, defalt&max is 5
        self.start()

    def start(self):
        self.loop = Process(target=self.main)
        self.loop.start()
        print(" * Listener PID:", self.loop.pid)

    def exit(self):
        self.loop.terminate()
        os.remove(self.location)
        print(" * Listener stopped")

    def main(self):
        while True:
            connection, address = self.sock.accept()
            try:
                connection.settimeout(5)
                buf = connection.recv(1024).decode("utf-8")
                print(' * Listener recieve:', buf)
                Process(
                    target=self.rules.match,
                    args=(buf, ),
                ).start()
            except socket.timeout:
                print(' * Listener time out')
        connection.close()
开发者ID:Siyuanw,项目名称:mySnort,代码行数:36,代码来源:msListener.py

示例7: query_results

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
def query_results(query):
    """
    Synchronously return results for an SQL query and return them as a dict to
    be sent back to clients.

    If the query takes too long, kill the query process and return an error
    instead.
    """
    conn = sqlite3.connect(config.DB_URI_READ_ONLY, uri=True)
    result_queue = Queue()

    query_process = Process(target=query_processor,
                            args=(conn, query, result_queue))
    query_process.start()
    query_process.join(config.QUERY_TIMEOUT_SECS)

    if query_process.is_alive():
        query_process.terminate()
        err = {'error': 'Query took too long; max time %s seconds' %
                        config.QUERY_TIMEOUT_SECS}
        return err

    output = result_queue.get()

    if type(output) is sqlite3.OperationalError:
        err = {'error': repr(output)}
        return err

    return output
开发者ID:mplewis,项目名称:narcissa,代码行数:31,代码来源:server.py

示例8: main

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
def main():

	port = common.PORT
	username = input("Choose a username : ")

	dark_vader, luke = Pipe()

	p = Process(target=server_process, args=(luke, port, username))
	p.start()

	def pause_handler(signum, frame):
		pass

	def chat_handler(signum, frame):
		print(u'\033[2K\n\033[1A',end='', flush=True)
		print(dark_vader.recv())
		print('{} > '.format(username), end="", flush=True)

	signal.signal(41, pause_handler)
	signal.signal(42, chat_handler)

	signal.pause()

	try:
		chat.chat(port, username)
	except (KeyboardInterrupt, SystemExit): # Handle the ctrl+c
		chat.broadcast(port, chat.encode(username, '{} leaved the chat'.format(username), special=True))
		print('*** Quitting ***')

	p.terminate()
开发者ID:PhiBabin,项目名称:l33tnet,代码行数:32,代码来源:main.py

示例9: StreamGatherer

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
class StreamGatherer():
    streamname = "mouseclicks"
    streamschema = {"type": "integer"}
    description = "Gathers the number of clicks made with the mouse"
    datatype = "action.count"

    def __init__(self):
        self.click_number = Value('i',0)
        self.clicklogger_process = None

    def start(self,cache):
        # Starts the background processes and stuff. The cache is passed, so that
        # if the gatherer catches events, they can be logged as they come in
        if self.clicklogger_process is None:
            self.clicklogger_process = Process(target=log_click_count,args=(self.click_number,))
            self.clicklogger_process.daemon = True
            self.clicklogger_process.start()

    def stop(self):
        if self.clicklogger_process is not None:
            self.clicklogger_process.terminate()
            self.clicklogger_process = None
            self.click_number.value = 0

    def run(self,cache):
        clk = self.clicks()
        if clk > 0:
            cache.insert(self.streamname,clk)


    #Gets the number of keypresses that are logged, and reset the counter
    def clicks(self):
        v = self.click_number.value
        self.click_number.value = 0
        return v
开发者ID:connectordb,项目名称:connectordb-laptoplogger,代码行数:37,代码来源:mouse.py

示例10: main

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
def main():
    func.mysql_exec("insert into mysql_bigtable_history SELECT *,LEFT(REPLACE(REPLACE(REPLACE(create_time,'-',''),' ',''),':',''),8) from mysql_bigtable",'')
    func.mysql_exec('delete from mysql_bigtable;','')
    #get mysql servers list
    servers = func.mysql_query('select id,host,port,username,password,tags,bigtable_size from db_servers_mysql where is_delete=0 and monitor=1 and bigtable_monitor=1;')
    if servers:
        print("%s: check mysql bigtable controller started." % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),));
        plist = []
        for row in servers:
            server_id=row[0]
            host=row[1]
            port=row[2]
            username=row[3]
            password=row[4]
            tags=row[5]
            bigtable_size=row[6]
            p = Process(target = check_mysql_bigtable, args = (host,port,username,password,server_id,tags,bigtable_size))
            plist.append(p)
        for p in plist:
            p.start()
        time.sleep(15)
        for p in plist:
            p.terminate()
        for p in plist:
            p.join()
        print("%s: check mysql bigtable controller finished." % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),))
开发者ID:crjfans,项目名称:lepus,代码行数:28,代码来源:check_mysql_bigtable.py

示例11: __run_tests

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
  def __run_tests(self, tests):
    logging.debug("Start __run_tests.")
    logging.debug("__name__ = %s",__name__)

    if self.os.lower() == 'windows':
      logging.debug("Executing __run_tests on Windows")
      for test in tests:
        self.__run_test(test)
    else:
      logging.debug("Executing __run_tests on Linux")
      # These features do not work on Windows
      for test in tests:
        if __name__ == 'benchmark.benchmarker':
          print textwrap.dedent("""
            -----------------------------------------------------
              Running Test: {name} ...
            -----------------------------------------------------
            """.format(name=test.name))
          test_process = Process(target=self.__run_test, args=(test,))
          test_process.start()
          test_process.join(self.run_test_timeout_seconds)
          if(test_process.is_alive()):
            logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
            self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
            test_process.terminate()
    logging.debug("End __run_tests.")
开发者ID:AbhijitDutta,项目名称:FrameworkBenchmarks,代码行数:28,代码来源:benchmarker.py

示例12: ProcessStarter

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
class ProcessStarter(object):
    
    def __init__(self):
        '''
        Setup the shared memory data structure model and initialize the control parts.
        '''
        self.running = True
        self.orprocess  = None
        self.guiprocess = None
        self.pipeGUI, self.pipeOR = Pipe()
        self.StartProcesses()

    def StartProcesses(self):
        self.guiprocess = Process(target=self.__startGUI__)
        self.guiprocess.start()        
        self.pipeGUI.send(["StartViewer", None])
        self.orprocess = Process(target=ORServer,args=(self.pipeOR,))
        self.orprocess.start()
        return True
    
    def terminate(self):
        try:
            self.pipeGUI.send(["Stop", None])
            self.guiprocess.terminate()
            self.orprocess.terminate()
        except:
            pass

    def __startGUI__(self):
        app  = QtGui.QApplication(sys.argv)
        form = pnpApp(self.pipeGUI, self)
        form.show()
        sys.exit(app.exec_())
开发者ID:rishabh-battulwar,项目名称:human_demos,代码行数:35,代码来源:ProcessStarter.py

示例13: checkAfsCredentials

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
 def checkAfsCredentials(self):
     '''
     we do an ssh connection to an AFS computer and return true if we manage
     to "land" on that computer
     TODO: very pseudo-method >>> find a better way
     '''
     if not self.afsuser or not self.afspw:
         self.parent.displayErrorMessage('Missing','No blank fields for AFS-credentials allowed')
         return
     
     comp = 'llc1'
     pw = 'echo \\\"'+self.afspw+'\\\"'
     p1 = subprocess.Popen(['echo "#!/bin/bash\n" > ~/pw.sh'],shell=True)
     p2 = subprocess.Popen(['echo '+pw+' >> ~/pw.sh'],shell=True)
     p3 = subprocess.Popen(['chmod a+x ~/pw.sh'],shell=True)        
     
     queue1 = Queue()
     p = Process(target=self.checkAfsCredentialsHelper,args=(comp,queue1))
     p.start()
     p.join(2)
     try:
         if queue1.get():  # we try to get the queue >> will throw an error after timeout
             subprocess.call(['rm ~/pw.sh'],shell=True)
             return True
     except IOError as e:
         subprocess.call(['rm ~/pw.sh'],shell=True)
         p.terminate()
         self.parent.displayErrorMessage('Error','Wrong AFS Password/Username!')
         return False
     except ValueError:
         print "value error"
         return False
开发者ID:arcaduf,项目名称:grecoman,代码行数:34,代码来源:connector.py

示例14: test_fork

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
    def test_fork(self):
        # Test using a client before and after a fork.
        if sys.platform == "win32":
            raise SkipTest("Can't fork on Windows")

        try:
            from multiprocessing import Process, Pipe
        except ImportError:
            raise SkipTest("No multiprocessing module")

        db = self._get_client().pymongo_test

        # Failure occurs if the client is used before the fork
        db.test.find_one()

        def loop(pipe):
            while True:
                try:
                    db.test.insert({"a": "b"})
                    for _ in db.test.find():
                        pass
                except:
                    traceback.print_exc()
                    pipe.send(True)
                    os._exit(1)

        cp1, cc1 = Pipe()
        cp2, cc2 = Pipe()

        p1 = Process(target=loop, args=(cc1,))
        p2 = Process(target=loop, args=(cc2,))

        p1.start()
        p2.start()

        p1.join(1)
        p2.join(1)

        p1.terminate()
        p2.terminate()

        p1.join()
        p2.join()

        cc1.close()
        cc2.close()

        # recv will only have data if the subprocess failed
        try:
            cp1.recv()
            self.fail()
        except EOFError:
            pass
        try:
            cp2.recv()
            self.fail()
        except EOFError:
            pass

        db.connection.close()
开发者ID:RockLi,项目名称:mongo-python-driver,代码行数:62,代码来源:test_replica_set_client.py

示例15: execute_action

# 需要导入模块: from multiprocessing import Process [as 别名]
# 或者: from multiprocessing.Process import terminate [as 别名]
    def execute_action(self, action):
        event = Event()
        queue = Queue()
        proc = Process(
            target=execute_action_proc,
            args=(self.execute, action, event, queue))
        proc.start()

        # Send heartbeat.
        heartbeat_retry = 0
        while not event.is_set():
            event.wait(config.ACTIVITY_HEARTBEAT_INTERVAL)
            try:
                res = self.heartbeat(self.task_token)
                if res['cancelRequested']:
                    proc.terminate()
                    proc.join()
                    return Result('cancelled', -1, '', '', '', -1)
            except Exception as err:
                if heartbeat_retry <= config.ACTIVITY_HEARTBEAT_MAX_RETRY:
                    heartbeat_retry += 1
                    continue
                else:
                    proc.terminate()
                    proc.join()
                    raise

        # Evaluate the result.
        result = queue.get_nowait()
        proc.join()
        return result
开发者ID:badboy99tw,项目名称:mass,代码行数:33,代码来源:__init__.py


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