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


Python Thread.terminate方法代码示例

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


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

示例1: WorkerReceiver

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
class WorkerReceiver(object):
    def __init__(self):
        print "Initializing WorkerReceiver class..."

    def _init(self):
        self.context = zmq.Context()
        self.bind_address = getattr(settings, "LOGSTREAM_BIND_ADDR", "ipc:///tmp/logstream_receiver")

        self.queue = Queue.Queue()

    def __call__(self):
        print "Running WorkerReceiver process..."

        self._init()
        self.socket = self.context.socket(zmq.PULL)
        self.socket.bind(self.bind_address)

        # Starting record processor thread.
        from threading import Thread

        self.worker = Thread(target=WorkerProcessor(), args=[self.queue])
        self.worker.daemon = True
        self.worker.start()

        # Record receiver loop.
        while True:
            data = self.socket.recv_pyobj()
            self.queue.put_nowait(data)

    def __del__(self):
        self.worker.terminate()
        self.socket.close()
开发者ID:niwinz,项目名称:django-logstream,代码行数:34,代码来源:base.py

示例2: bench

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
def bench( server_func, client_func, client_count,
           server_kwds=None, client_kwds=None, client_max=10, server_join_timeout=1.0 ):
    """Bench-test the server_func (with optional keyword args from server_kwds) as a process; will fail
    if one already bound to port.  Creates a thread pool (default 10) of client_func.  Each client
    is supplied a unique number argument, and the supplied client_kwds as keywords, and should
    return 0 on success, !0 on failure.

    : Both threading.Thread and multiprocessing.Process work fine for running a bench server.
    However, Thread needs to use the out-of-band means to force server_main termination (since we
    can't terminate a Thread).  This is implemented as a container (eg. dict-based cpppo.apidict)
    containing a done signal.

    """

    #from multiprocessing 	import Process
    from threading 		import Thread as Process

    from multiprocessing.pool	import ThreadPool as Pool
    #from multiprocessing.dummy	import Pool
    #from multiprocessing	import Pool
    import time
    import json

    log.normal( "Server %r startup...", misc.function_name( server_func ))
    server			= Process( target=server_func, kwargs=server_kwds or {} )
    server.daemon		= True
    server.start()
    time.sleep( .25 )

    try:
        log.normal( "Client %r tests begin, over %d clients (up to %d simultaneously)", 
                    misc.function_name( client_func ), client_count, client_max )
        pool			= Pool( processes=client_max )
        # Use list comprehension instead of generator, to force start of all asyncs!
        asyncs			= [ pool.apply_async( client_func, args=(i,), kwds=client_kwds or {} )
                                    for i in range( client_count )]
        successes		= sum( not a.get()
                                       for a in asyncs )

        failures		= client_count - successes
        log.normal( "Client %r tests done: %d/%d succeeded (%d failures)", misc.function_name( client_func ),
                  successes, client_count, failures )
        return failures
    finally:
        # Shut down server; use 'server.control.done = true' to stop server, if
        # available in server_kwds.  If this doesn't work, we can try terminate
        control			= server_kwds.get( 'server', {} ).get( 'control', {} ) if server_kwds else {}
        if 'done' in control:
            log.normal( "Server %r done signalled", misc.function_name( server_func ))
            control['done']	= True	# only useful for threading.Thread; Process cannot see this
        if hasattr( server, 'terminate' ):
            log.normal( "Server %r done via .terminate()", misc.function_name( server_func ))
            server.terminate() 		# only if using multiprocessing.Process(); Thread doesn't have
        server.join( timeout=server_join_timeout )
        if server.is_alive():
            log.warning( "Server %r remains running...", misc.function_name( server_func ))
        else:
            log.normal( "Server %r stopped.", misc.function_name( server_func ))
开发者ID:dpasquazzo,项目名称:cpppo,代码行数:60,代码来源:network.py

示例3: Orderbook

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
class Orderbook(object):

	def __init__(self, uuid):
		self.uuid = uuid # + uuid4().hex
		self.keymanager = RedisKeyManager(uuid)				
		self.buy_orders = list()
		self.sell_orders = list()
		self.redis = Redis()
		logger.info('Initializing orderbook: %s'%self.uuid)
				
	
	def start_auction(self):
		""" Run this to start the auction. If the auction is already running, nothing happens"""
		if not hasattr(self, 'daemon'):
			self.daemon = Thread(name = 'auction_%s'%self.uuid, target = self.queue_daemon)		
			self.daemon.start()
			# self.osn = Thread(name = 'orderbookstatus_%s'%self.uuid, target = self.orderbook_status_notifier)		
			# self.osn.start()
			

			# Auction.query.filter_by(uuid = self.uuid).update({'running' : True})
			
			logger.info('Started auction for book %s'%self.uuid)
		else:
			logger.info('Auction is already running at book %s'%self.uuid)

	
	def stop_auction(self):
		if hasattr(self, 'daemon'):
			self.daemon.terminate()
			# Auction.query.filter_by(uuid = self.uuid).update({'running' : False})
			del self.daemon
			logger.info('Terminated auction at book %s'%self.uuid)
		else:
			logger.info('Cannot stop auction that is not already running at book %s'%self.uuid)

	
	def queue_daemon(self, rv_ttl=500):
		""" 
		The daemon that listens for incoming orders. Must be run in a separate process. 
		All received orders are stored in the database
		"""
		while True:
			logger.debug('Waiting for orders...')
			order_form_data = self.redis.blpop(prefixed(self.uuid))
			order_form_data = loads(order_form_data[1])
			new_order = Order(**order_form_data)
			self.store_order(new_order)
			try:
				response = self.process_order(new_order)
				logger.debug('Finished processing order.')
			except Exception, e:
				logger.exception(e)
				response = e
开发者ID:halfdanrump,项目名称:shitcoin_market,代码行数:56,代码来源:orderbook.py

示例4: Audio_Capture

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
class Audio_Capture(object):
    """
    PyAV based audio capture.
    """

    def __init__(self, file_loc,audio_src=0):
        super(Audio_Capture, self).__init__()

        try:
            file_path,ext = file_loc.rsplit('.', 1)
        except:
            logger.error("'%s' is not a valid media file name."%file_loc)
            raise Exception("Error")

        if ext not in ('wav'):
            logger.error("media file container should be wav. Using a different container is not supported.")
            raise NotImplementedError()

        self.should_close = Event()
        self.process = None

        self.start(file_loc,audio_src)

    def start(self,file_loc, audio_src):
        # from rec_thread import rec_thread
        try:
            from billiard import forking_enable
            forking_enable(0)
        except ImportError:
            pass
        self.should_close.clear()
        self.process = Process(target=rec_thread, args=(file_loc, audio_src,self.should_close))
        self.process.start()
        try:
            forking_enable(1)
        except:
            pass

    def stop(self):
        self.should_close.set()
        self.process.join(timeout=1)
        try:
            self.process.terminate()
        except:
            logger.error('Could not joind recording thread.')
        self.process = None

    def close(self):
        self.stop()

    def __del__(self):
        if self.process:
            self.stop()
开发者ID:nievamartin10,项目名称:pupil,代码行数:55,代码来源:av_writer.py

示例5: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
    def run(self):
        try:
            # init replica thread
            t_replica = Thread(target = self.replicaThread, args=())
            t_replica.start()

            while(1):
                conn, addr = self.socket.accept() # accept
                print('Connected by', addr) # addr = (host, port)
                # init a server thread for a client
                t_serverThread = Thread(target = self.serverThread, args=(conn, ))
                t_serverThread.start()
        except:
            print("CTRL C occured")
        finally:
            print("exit server thread")
            self.socket.close()
            t_replica.terminate()
开发者ID:weiyangedward,项目名称:cs425_MP,代码行数:20,代码来源:server.py

示例6: preview

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
    def preview(self, port=3131):
        processWatcher = Thread(target=self.regenerate)
        processWatcher.start()
        self.generate()

        from http.server import HTTPServer, SimpleHTTPRequestHandler

        HandlerClass = SimpleHTTPRequestHandler
        HandlerClass.protocol_version = "HTTP/1.1"
        ServerClass = HTTPServer
        server_address = ('', port)
        httpd = ServerClass(server_address, HandlerClass)
        sa = httpd.socket.getsockname()
        os.chdir(self.sitepath)
        print("Serving HTTP on", sa[0], "port", sa[1], "...")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nKeyboard interrupt received, exiting.")
            processWatcher.terminate()
            httpd.server_close()
            sys.exit(0)
开发者ID:mjnaderi,项目名称:mikidown,代码行数:24,代码来源:generator.py

示例7: Manager

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]

#.........这里部分代码省略.........
                if event.failure is not None:
                    error = (etype, evalue, format_tb(etraceback))
                    self.fire(Failure(event, handler, error), *event.failure)

            if retval is not None:
                if retval and attrs["filter"]:
                    if event.filter is not None:
                        self.fire(Filter(event, handler, retval), *event.filter)
                    return  # Filter
                if event.success is not None:
                    self.fire(Success(event, handler, retval), *event.success)

        if event.end is not None:
            self.fire(End(event, handler, retval), *event.end)

    def _signalHandler(self, signal, stack):
        self.fire(Signal(signal, stack))
        if signal in [SIGINT, SIGTERM]:
            self.stop()

    def start(self, sleep=0, log=True, link=None, process=False):
        group = None
        target = self.run
        name = self.__class__.__name__
        mode = "P" if process else "T"
        args = (sleep, log, mode)

        if process and HAS_MULTIPROCESSING:
            if link is not None and isinstance(link, Manager):
                from circuits.net.sockets import Pipe
                from circuits.core.bridge import Bridge
                from circuits.core.utils import findroot

                root = findroot(link)
                parent, child = Pipe()
                self._bridge = Bridge(root, socket=parent)
                self._bridge.start()
                args += (child,)

            self._task = Process(group, target, name, args)
            self._task.daemon = True
            if HAS_MULTIPROCESSING == 2:
                setattr(self._task, "isAlive", self._task.is_alive)
            self.tick()
            self._task.start()
            return

        self._task = Thread(group, target, name, args)
        self._task.setDaemon(True)
        self._task.start()

    def stop(self):
        self._running = False
        self.fire(Stopped(self))
        if self._task and type(self._task) is Process and self._task.isAlive():
            if not current_process() == self._task:
                self._task.terminate()
        self._task = None
        self.tick()

    def tick(self):
        if self._ticks:
            try:
                [f() for f in self._ticks.copy()]
            except:
                etype, evalue, etraceback = _exc_info()
                self.fire(Error(etype, evalue, format_tb(etraceback)))
        if self:
            self._flush()

    def run(self, sleep=0, log=True, __mode=None, __socket=None):
        if not __mode == "T" and current_thread().getName() == "MainThread":
            if os.name == "posix":
                _registerSignalHandler(SIGHUP, self._signalHandler)
            _registerSignalHandler(SIGINT, self._signalHandler)
            _registerSignalHandler(SIGTERM, self._signalHandler)

        if __socket is not None:
            from circuits.core.bridge import Bridge

            manager = Manager()
            bridge = Bridge(manager, socket=__socket)
            self.register(manager)
            manager.start()

        self._running = True

        self.fire(Started(self, __mode))

        try:
            while self or self.running:
                self.tick()
                if sleep:
                    time.sleep(sleep)
        finally:
            if __socket is not None:
                while bridge or manager:
                    pass
                manager.stop()
                bridge.stop()
开发者ID:AlphaStaxLLC,项目名称:TundraAddons,代码行数:104,代码来源:manager.py

示例8: NodeGenerator

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]

#.........这里部分代码省略.........
        while not bind:
            try:
                # print self.port
                self.socket.bind((self.ip, self.port))
                bind = True
                print("Client created on %s listening to port %s" % (self.ip, self.port))
            except socket.error:
                self.port += 1

        # tell my listening port and address to the network admin
        admin = socket.socket()
        admin.connect(self.network_address)
        admin.send(json.dumps({'type': 'intro', 'data': {'port': self.port, 'ip': self.ip, 'loc': self.loc}}))
        admin.close()
        while True:
            self.socket.listen(5)
            connection, address = self.socket.accept()
            self.process_message(connection.recv(BUFFER_SIZE))

    def process_message(self, msg):
        try:
            message = json.loads(msg)
            if message['type'] == 'admin_broadcast':
                data = message['data']
                print "BROADCAST: %s" % data
            if message['type']== 'neighbor_info':
                data=message['data']
                print data
                self.neighbors = self.neighbors+data
                print "NEIGHBOURS : %s "% self.neighbors
                print "NEIGHBOR INFO: %s" % data
            if message['type'] == 'object_info':
                data = message['data']
                print ""
                print "OBJECTDATA : %s" % data
                for entry in data['history']:
                    entry['object']= data['object']
                    self.write_to_file(json.dumps(entry))
                self.objects[data['object']]['history']= self.objects[data['object']]['history'] + data['history']
            if message['type'] == 'heartbeat':
                data = message['data']
                self.log("HEARTBEAT : %s" % str(data))
                #print "HEARTBEAT : %s" % data
            #print ""
        except Exception:
            raise
            print 'Bad Message received: %s' % msg

    def message(self,address, msg):
        s = socket.socket()
        s.connect(address)
        s.send(msg)
        s.close()
            

    def broadcast_neighbours(self, message):
        for node in self.neighbors:
            #print "Broadcast to %s" % node
            try :
                self.message((node["ip"],node["port"]),message)
            except Exception:
                print "Cannot reach Neighbour %s" % node

    def send_heartbeat(self):
        while True:
            time.sleep(5)
            self.heartbeat()

    def heartbeat(self):
            self.broadcast_neighbours(json.dumps({'type': 'heartbeat', 'data': {'port': self.port, 'ip': self.ip, 'loc': self.loc}}))

    def stop(self):
        self.listener.terminate()
        sys.exit(0)

    def generate_report(self):
        name = raw_input("Enter the Object name to analyse:")
        if name not in self.objects.keys():
            print "Cannot find object"
            return
        object = self.objects[name]
        history = object['history']
        history.sort(key = lambda d: d['ts'])
        x_pts = []
        y_pts = []
        labels = []
        for entry in history:
            x_pts.append(entry['loc'][0])
            y_pts.append(entry['loc'][1])
            labels.append(entry['ts'])
        plt.plot(x_pts,y_pts,marker='o', label="Trajectory of "+ name)



    def start(self):
        self.listener.start()
        self.heartbeat_generator.start()
        if TRACK:
            self.track()
            pass
开发者ID:ashriths,项目名称:img-proc,代码行数:104,代码来源:node_generator.py

示例9: information

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]

#.........这里部分代码省略.........

        # Board ID
        self.board_type = 0
        self.hw_rev = 0
        self.fw_ver_major = 0
        self.fw_ver_minor = 0

        self.last_sensor_timestamp = 0
        self.last_update_time = 0.0

        self.integrator = InertialDataIntegrator()
        self.yaw_angle_tracker = ContinuousAngleTracker()
        self.yaw_offset_tracker = OffsetTracker(self.YAW_HISTORY_LENGTH)
        self.quaternion_history = TimestampedQuaternionHistory()

        self.lock = Lock()
        self.io = I2C_IO(self, self.update_rate_hz)
        if start_immediately:
            self.start()

    def start(self):
        self.t = Thread(target=self.io.run, name="AHRS_I2C")
        self.t.start()

    def stop(self):
        self.running = False
        self.io.stop()

    def free(self):
        self.stop()

        self.t.join(timeout=5)
        if self.t.is_alive():
            self.t.terminate()

    def response(self, child_conn):
        self.running = True

        if not hasattr(self, 't') or self.t is None or self.t.is_alive() is False:
            self.start()

        while self.running:
            if child_conn.poll():
                cmd = child_conn.recv()
            else:
                time.sleep(.01)
                continue
            if cmd == ProcessCommands.TIME:
                child_conn.send(self.get_last_time_stamp())
            elif cmd == ProcessCommands.YAW:
                child_conn.send(self.get_yaw())
            elif cmd == ProcessCommands.PITCH:
                child_conn.send(self.get_pitch())
            elif cmd == ProcessCommands.ROLL:
                child_conn.send(self.get_roll())
            elif cmd == ProcessCommands.COMPASS_HEADING:
                child_conn.send(self.get_compass_heading())
            elif cmd == ProcessCommands.ZERO_YAW:
                self.zero_yaw()
                child_conn.send("ok")
            elif cmd == ProcessCommands.IS_CALIBRATING:
                child_conn.send(self.is_calibrating())
            elif cmd == ProcessCommands.IS_CONNECTED:
                child_conn.send(self.is_connected())
            elif cmd == ProcessCommands.BYTE_COUNT:
                child_conn.send(self.get_byte_count())
开发者ID:utk-robotics-2017,项目名称:navX-Python,代码行数:70,代码来源:ahrs.py

示例10: range

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
    

if __name__ == '__main__':

    for i in range(10):
        print("Parent: iteration %d" % i)
        print("Parent: Creating child Thread.")
        q = Queue()
        t0 = time()
        t = Thread(target=child, args=(q, t0))
        t.daemon = True
        # print("Parent: Starting child thread.")
        t.start()
        # print("Parent: waiting some seconds.")
        sleep(1)

        if not q.empty():
            t_child = q.get()
            print("Parent: got this from child thread %ssec." % t_child)
        else:
            print("Parent: nothing arrived from child thread.")
                
        if t.is_alive():
            print("Parent: terminating child thread.")
            t.terminate()

        print("Parent: child thread terminated.")
        print("")
        print("")

开发者ID:emanuele,项目名称:mockups,代码行数:31,代码来源:mockup_thread.py

示例11: Node

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]

#.........这里部分代码省略.........
                    else:
                        if event.type == MessageTypes.Insert:
                            self.send_failure(event)

            self.table.sync(new_table, self.id, data['node_id'])
        print(self.table.table)

    def send(self, _id, event=None):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            data = "data"
           # print("Sending Data from client")
            # Connect to server and send data
            sock.settimeout(3)
            sock.connect((Node.ips[_id], 6000))
            sock.sendall(event)

            # Receive data from the server and shut down
            received = sock.recv(1024)
            # Add To EntrySet
        except:
            # Node Down cancel conflict
            if not event == None:
                print("Failed to connect to node: " + str(_id))
                d = json.loads(event)
                dd = json.loads(d['events'][0])
                event = Event.load(dd)
                event.entry = Entry.load(event.entry)
                self.delete_entry(event.entry, [_id])
            pass

        finally:
            sock.close()

    def send_failure(self, event):
        #grab id from event

        print("Sending Failure command")
        data = {
            'node_id': self.id,
            'type': 'failure',
            'event': event.to_JSON()
        }

        self.send(event.node, json.dumps(data))

    def rec_failure(self, data):
        event = Event.load(json.loads(data['event']))
        event.entry = Entry.load(event.entry)

        self.delete_entry(event.entry)

    # Check if a node has a certain event
    def has_event(self,event, node_id):
        return self.table.get(node_id, event.node) >= event.time

    def send_to_node(self, node_id):
        # Don't send anything if the node is this
        if node_id == self.id:
            return

        partial = []
        for event in self.events:
            if not isinstance(event, Event):
                continue
            if not self.has_event(event, node_id):
                partial.append(event.to_JSON())

        data = {
            'type': 'sync',
            'node_id': self.id,
            'table': self.table.to_JSON(),
            'events': partial,
        }

        self.send(node_id, json.dumps(data))

    def add_entry(self, entry):
        event = Event(MessageTypes.Insert, time.time(), self.id, entry)
        self.table.update(self.id, time.time() + 0.1)
        event.apply(self.entry_set, self)
        self.events.append(event)

        for id in entry.participants:
            if not id == self.id:
                self.send_to_node(id)

    def delete_entry(self, entry, exclude=[]):
        event = Event(MessageTypes.Delete, time.time(), self.id, entry)
        self.table.update(self.id, time.time() + 0.1)
        event.apply(self.entry_set, self)
        self.events.append(event)

        for id in entry.participants:
            if not id == self.id:
                if not id in exclude:
                    self.send_to_node(id)

    def kill_thread(self):
        self.thread.terminate()
开发者ID:axptwig,项目名称:Wu-Bernstein-Distributed-Systems-Implementation,代码行数:104,代码来源:node.py

示例12: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
    def run(self, cluster=None, verbose=False):
        """
        Runs all the tasks in a smart order with many at once. Will not return until all tasks are done.

        Giving a cluster (as a Cluster object) means that the cluster is used for any tasks that are added with can_run_on_cluster=True.
        
        Setting verbose to True will cause the time and the command to print whenever a new command is about to start.
        """

        # Checks
        if self.__conditional != None: raise ValueError('Tasks already running')
        if  len(self.inputs) == 0 and len(self.generators) == 0  and len(self.outputs) == 0 and len(self.cleanups) == 0 : return
        if (len(self.inputs) == 0 and len(self.generators) == 0) or (len(self.outputs) == 0 and len(self.cleanups) == 0): raise ValueError('Invalid set of tasks (likely cyclic)')
        prev_signal = None

        try:
            # Create basic variables and lock
            self._cluster = cluster
            self.__error = False
            self.__killing = False
            self.__conditional = Condition() # for locking access to Task.done, cpu_pressure, mem_pressure, next, last, log, and error
            self.__running = set()

            # Setup log
            done_tasks = self.__process_log() if exists(self.logname) else ()
            self.__log = open(self.logname, 'w', 0)
            for k,v in self.settings.items(): self.__log.write("*"+k+"="+str(v)+"\n")
            # TODO: log overall inputs and outputs
            for dc in done_tasks:
                if verbose: print("Skipping " + dc[20:].strip())
                self.__log.write(dc+"\n")
            if verbose and len(done_tasks) > 0: print('-' * 80)
            self._rusagelog = open(self.rusage_log, 'a', 1) if self.rusage_log else None

            # Calcualte the set of first and last tasks
            self.__calc_next() # These are the first tasks
            last = {self.outputs[f] for f in self.overall_outputs()}
            last |= self.cleanups
            if len(last) == 0: raise ValueError('Tasks are cyclic')
            self.__last = {t for t in last if not t.done}

            # Get the initial pressures
            self.__cpu_pressure = 0
            self.__mem_pressure = get_mem_used_by_tree() + 1*MB # assume that the creation of threads and everything will add some extra pressure

            # Set a signal handler
            try:
                from signal import signal, SIGUSR1
                prev_signal = signal(SIGUSR1, self.display_stats)
            except: pass

            # Keep running tasks in the tree until we have completed the root (which is self)
            with self.__conditional:
                while len(self.__last) != 0:
                    # Get next task (or wait until all tasks or finished or an error is generated)
                    while len(self.__last) > 0 and not self.__error:
                        task = self.__next_task()
                        if task != None: break
                        self.__conditional.wait(30) # wait until we have some available [without the timeout CTRL+C does not work and we cannot see if memory is freed up on the system]
                    if len(self.__last) == 0 or self.__error: break

                    # Run it
                    self.__running.add(task)
                    t = Thread(target=self.__run, args=(task,))
                    t.daemon = True
                    if verbose: print(strftime(Tasks.__time_format) + " Running " + str(task))
                    t.start()
                    sleep(0) # make sure it starts

                # There was an error, let running tasks finish
                if self.__error and len(self.__running) > 0:
                    write_error("Waiting for other tasks to finish running.\nYou can terminate them by doing a CTRL+C.")
                    while len(self.__running) > 0:
                        self.__conditional.wait(60) # wait until a task stops [without the timeout CTRL+C does not work]

        except KeyboardInterrupt:

            # Terminate and kill tasks
            write_error("Terminating running tasks")
            with self.__conditional:
                self.__killing = True
                for t in self.__running:
                    try: t.terminate()
                    except: pass
                secs = 0
                while len(self.__running) > 0 and secs < 10:
                    self.__conditional.wait(1)
                    secs += 1
                for t in self.__running:
                    try: p.kill()
                    except: pass

        finally:
            # Cleanup
            if prev_signal: signal(SIGUSR1, prev_signal)
            if hasattr(self, '__log'):
                self.__log.close()
                del self.__log
            if hasattr(self, '_rusagelog'):
                if self._rusagelog: self._rusagelog.close()
#.........这里部分代码省略.........
开发者ID:david-hoffman,项目名称:py-seg-tools,代码行数:103,代码来源:tasks.py

示例13: lprint

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
    elif started and otherUser:
      lprint('other users loged in. killing the process...')
      kill(pid)
      lprint('killed')
      started = False
    elif not started and not otherUser:
      lprint('starting the process...')
      pid = os.fock()
      if pid == 0: 
        Popen(['ssh', '-t', hostname, cmd])
        sys.exit(0)
      else:
        started = True

    time.sleep(1)


cmd = raw_input('input command:')

ps = []
for i in range(2,5):
  hostname = 'galaxy{:03d}'.format(i)

  p = Thread(target = worker, args = (hostname, cmd))
  ps.append(p)
  p.start()

raw_input('press enter to terminate...')
for p in ps:
  p.terminate()
开发者ID:chenghuiren,项目名称:galaxy,代码行数:32,代码来源:runidle.py

示例14: Player

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
class Player():
    def __init__(self):
        self.playlist = []
        self.internal_play_flag = False
        self.player_state = "Stopped"
        self.player_thread = None
        # self.player_thread = Thread(target=self.build_player)
        # self.player_thread.start()

        """ Allow dbus to be refreshed """
        sleep(1)
        """ Allow dbus to be refreshed """

        # self.bus = dbus.SessionBus()
        self.proxy = None
        self.player = None
        self.properties_manager = None
        # self.properties_manager.Set('org.mpris.MediaPlayer2.Player', 'Volume', .7) # Set initial volume

        self.watcher_thread = None
        # self.watcher_thread = Thread(target=self.build_watcher)
        # self.watcher_thread.start()

    def build_player(self):
        Popen(['cvlc', '--control', 'dbus'])
        self.bus = dbus.SessionBus()
        self.proxy = self.bus.get_object('org.mpris.MediaPlayer2.vlc','/org/mpris/MediaPlayer2')
        self.player = dbus.Interface(self.proxy, 'org.mpris.MediaPlayer2.Player')
        self.properties_manager = dbus.Interface(self.proxy, 'org.freedesktop.DBus.Properties')
        self.properties_manager.Set('org.mpris.MediaPlayer2.Player', 'Volume', .7) # Set initial volume

    def build_watcher(self):
        while True:
            try:
                """ Are we playing back or stopped? """
                if (self.internal_play_flag == True):
                    """ If playback is just stopped and there is more in the queue it's time to move the queue """
                    if ((self.get_playback_status() == "Stopped") & (len(self.playlist) > 0)):
                        try:
                            print "##### Playing next track. #####"
                            """ Remove the last played item """
                            self.playlist.pop(0)
                            """ Open the next Uri"""
                            self.open_uri(self.playlist[0].url)
                            urlopen('http://localhost:5000/new_track')
                        except:
                            print "##### The queue is empty. #####"
                            self.player_state = "Stopped"
                            self.player_thread.terminate()
                            self.watcher_thread.terminate()
                            urlopen('http://localhost:5000/new_track')
                            urlopen('http://localhost:5000/player_state')
                            """ There is nothing to play - I think vlc will naturally handle it."""
                # print "##### Playing and playlist greater than 0 #####"
                sleep(1)
            except:
                print self.get_playback_status()
                sleep(1)

    """ Add a stream from youtube """

    def add_stream_from_youtube(self, youtube_url): # returns stream object
        if (youtube_url.startswith('http')):
            url = youtube_url
        else:
            url = 'https://www.youtube.com/watch?v=' + str(youtube_url)
        try:
            video = pafy.new(url)
            audiostreams = video.audiostreams
            best = video.getbestaudio()
            s = Stream(best.title, best.url)
            self.playlist.append(s)
            if (len(self.playlist) == 1):
                self.player_thread = Thread(target=self.build_player())
                self.watcher_thread = Thread(target=self.build_watcher())
                self.player_thread.start()
                self.watcher_thread.start()
                self.play_or_pause()
                self.player_state = "Playing"
                urlopen('http://localhost:5000/new_track')
                urlopen('http://localhost:5000/player_state')
        except:
            print "had a problem adding"

    """ Stop player process """

    def kill_player(self):
        self.internal_play_flag = False
        self.player_thread.terminate()
        self.watcher_thread.terminate()

    """ Play next in queue """

    def play_next(self):
        if ((self.internal_play_flag == False) & len(self.playlist) > 1): # Begin playing if we are stopped and hit next
            self.internal_play_flag = True
        try:
            print "##### Buffering the next track #####" # Try to play the next track
            self.player_state = "Buffering"              # Set our state to buffering
            urlopen('http://localhost:5000/player_state')# Update state
#.........这里部分代码省略.........
开发者ID:stevemurr,项目名称:raspberry-jukebox-youtube,代码行数:103,代码来源:player.py

示例15: stream

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import terminate [as 别名]
class RGBDStreamer:
    """
    This class is capable of browsing through an RGB-D data stream (videos, devices) while calibrating the data

    """
    pclStreamer = RGBDCalibration()  # Creates a single static copy of the PCL based streamer object

    def __init__(self, frame_callback=None, connection_callback=None, calibrate=True, state_function=None, blocking=True):
        """
        Starts the RGBD streamer object

        The parameters are the following:

        - frame_callback: a callback function this object will call whenever a new calibrated RGBD frame is available
        - connection_callback: this is called whenever there is an update in the connection.
        - calibrate: Whether to calibrate the RGB-D data or not. If not, then the only thing it's retrieved are the
                     RGB and Depth frames.
        - stateFunction: This is a function which this module calls as soon as a new RGB-D frame is read. It is useful
                     to capture external information with timing as close as possible to the timing a frame is read
        """
        # Configuring the behavior
        self.frame_callback = frame_callback
        self.connection_callback = connection_callback
        self.calibrate = calibrate
        self.state_function = state_function
        self.blocking = blocking  # Blocking behavior for the caller application
        # Inner states
        self.streamLoopRunning = True
        self.paused = False
        self.delta  = False

        # The source object for recorded RGB-D data. Devices data sources are handled inside pclStreamer
        self.recordedSource = None
        # The object with the relevant calibration data
        self.KDH = RGBDCamera()
        # By providing the references to the PCLStreamer of the cameras, it should be enough to do the calibration
        self.pclStreamer.setCameras(self.KDH.rgb_camera, self.KDH.depth_camera)
        self.connected = False
        self.N_frames = 100
        # The fifo of frames
        self.FIFO = deque()
        self.frameLock = Lock()
        self.recordingsLock = Lock()
        self.frameIndex = -1

        # Inner thread which is retrieving calibrated frames
        self.streamThread = Thread(target=self.streamLoop)
        self.streamThread.start()

        # Inner thread which is reading recorded RGB-D data (e.g. video files). Emulates a behavior like OpenNI but,
        # due to python restrictions, it would still run in the same CPU as the main thread
        self.RGBDReadThread = Thread(target=self.readRecordedLoop)
        self.RGBDReadThread.start()

    def kill(self):
        self.disconnect()
        self.streamLoopRunning = False# This should eventually kill the listening thread
        if self.streamThread.is_alive():
            self.streamThread.join(0.5)
            if self.streamThread.is_alive():
                self.streamThread.terminate()
        if self.RGBDReadThread.is_alive():
            self.RGBDReadThread.join(0.5)
            if self.RGBDReadThread.is_alive():
                self.RGBDReadThread.terminate()

    def __del__(self):
        self.kill()

    def setStateFunction(self, state_function=None):
        self.state_function = state_function

    def toggleConnect(self, devFile=0, calFile=None):
        if self.connected:
            self.disconnect()
        else:
            self.connect(devFile, calFile)

    def connect(self, source_description=0, calFile=None):
        """
        According to source_description this will establish a connection to the specified source of RGBD data

        The options of sources of data are the diverse. An integer refers to a the connected camera with that same index.
        A string normally refers to the path to recorded data. According to the extension we'll decide on the source
        object which will be created to manage it.

        We can also specify a calibration file. Even though OpenNI is handling some calibration (registration between
        depth and rgb), we still have the option to override that by specifying the calibration file to be used.
        """
        if self.connected:
            self.disconnect()
        self.pause(True)
        self.pclStreamer.setCalibration(self.calibrate)
        if source_description.__class__ is int:
            # If we are connecting to a device
            if config.CONNECTED_DEVICE_SUPPORT:
                self.pclStreamer.connectDevice(source_description)
                if self.calibrate:
                    if calFile is not None:
                        self.KDH.setCalibration(calFile)
#.........这里部分代码省略.........
开发者ID:caomw,项目名称:rgbd-1,代码行数:103,代码来源:RGBDStreamer.py


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