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


Python Thread.daemon方法代码示例

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


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

示例1: start_watching

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
def start_watching(tasks, syncmap, stores, cpool, period=60):
    # for imap stores run threads tracking remote mailboxes
    for stname, box, path in syncmap:
        store = stores[stname]
        if 'imapstore' in store:

            def makecon(con, store=store):
                if con:
                    logger.debug('trying to reconnect')
                    return cpool.reconnect(
                        con, store['pass'], store['ssltype'])
                else:
                    return cpool.get_or_create_connection(
                        store['host'], store['user'], store['pass'],
                        store['port'], store['ssltype'])

            callback = get_watch_callback(tasks, stname, box, path)
            t = Thread(target=watch_errors,
                       args=(makecon, path, callback, tasks))
            t.daemon = True
            t.start()
    # run a single thread tracking all maildir changes
    t = Thread(target=watch_local, args=(tasks, period))
    t.daemon = True
    t.start()
开发者ID:vlevit,项目名称:mbwatch,代码行数:27,代码来源:mbwatch.py

示例2: test_record_lock

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
        def test_record_lock(self):
            shlock = SHLock()
            lock = RecordLock(shlock)

            shlock.acquire()
            self.assertRaises(LockingError, lock.lock, 1)
            shlock.release()
            with lock.lock(1):
                with lock.lock(1):
                    pass

            def dolock():
                with lock.lock(1):
                    time.sleep(0.1)

            t = Thread(target=dolock)
            t.daemon = True
            with lock.lock(1):
                t.start()
                t.join(0.2)
                self.assertTrue(t.is_alive())
            t.join(0.11)
            self.assertFalse(t.is_alive())

            t = Thread(target=dolock)
            t.daemon = True
            with lock.lock(2):
                t.start()
                t.join(0.11)
                self.assertFalse(t.is_alive())
开发者ID:BobPyron,项目名称:calibre,代码行数:32,代码来源:locking.py

示例3: start

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
 def start(self, shell_command):
     """Start a command running in the sandbox"""
     if self.is_alive:
         raise SandboxError("Tried to run command with one in progress.")
     working_directory = self.working_directory
     self.child_queue = Queue()
     shell_command = shlex.split(shell_command.replace('\\','/'))
     try:
         self.command_process = subprocess.Popen(shell_command,
                                                 stdin=subprocess.PIPE,
                                                 stdout=subprocess.PIPE,
                                                 stderr=subprocess.PIPE,
                                                 cwd=working_directory)
     except OSError:
         raise SandboxError('Failed to start {0}'.format(shell_command))
     self._is_alive = True
     stdout_monitor = Thread(target=_monitor_file,
                             args=(self.command_process.stdout, self.stdout_queue))
     stdout_monitor.daemon = True
     stdout_monitor.start()
     stderr_monitor = Thread(target=_monitor_file,
                             args=(self.command_process.stderr, self.stderr_queue))
     stderr_monitor.daemon = True
     stderr_monitor.start()
     Thread(target=self._child_writer).start()
开发者ID:pombreda,项目名称:aichallenge-1,代码行数:27,代码来源:sandbox.py

示例4: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
    def run(self):
        """
        Run the Component and Client threads, start listening or polling (depending on the configuration),
        and periodically check for received messages

        """
        if self.config is not None:

            # start listening if Client or Component are Listeners
            if (("Client" in self.config and "Listener" in self.config["Client"]) or
                ("Component" in self.config and "Listener" in self.config["Component"])):
                t_listen = Thread(target=self.listen_in_background)
                t_listen.daemon = True
                t_listen.start()

            # start polling if Client is Initiator (InitiatorComponent is handled in handle_message())
            if "Initiator" in self.config["Client"]:
                t_poll = Thread(target=self.poll_in_background)
                t_poll.daemon = True
                t_poll.start()
        else:

            # default: both Client and Component are listeners
            t_listen = Thread(target=self.listen_in_background)
            t_listen.daemon = True
            t_listen.start()

        # check for messages received from Client thread
        while True:
            if not self.from_cli.empty():
                [msg, identity] = self.from_cli.get()
                self.handle_message(msg, identity)
            sleep(0.1)
开发者ID:mami-project,项目名称:mplane-sdk,代码行数:35,代码来源:supervisor.py

示例5: convert

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
 def convert(self, config):
     self.reset()
     for file_path in self.file_paths:
         if self.cancel_event.is_set():
             break
         basename = os.path.basename(file_path)
         dirname = os.path.dirname(file_path)
         outfile_path = os.path.join(dirname, '[8bit]' + basename)
         tmpfile_path = os.path.join(dirname, '[TMP]' + basename)
         try:
             self.process = Popen(
                 [config['x264'], '--preset', config['preset'], '--tune',
                  config['tune'], '--crf', config['crf'], '--quiet',
                  file_path, '--output', tmpfile_path], stdout=PIPE,
                 stderr=STDOUT, bufsize=1, close_fds=ON_POSIX,
                 universal_newlines=True)
             t = Thread(target=enqueue_output, args=(self.process.stdout, self.output_queue))
             t.daemon = True
             t.start()
             self.process.wait()
             self.process = Popen(
                 [config['mkvmerge'], tmpfile_path,
                  '-D', file_path, '-o', outfile_path],
                 stdout=PIPE, stderr=STDOUT, bufsize=1,
                 close_fds=ON_POSIX, universal_newlines=True
             )
             t = Thread(target=enqueue_output, args=(self.process.stdout, self.output_queue))
             t.daemon = True
             t.start()
             self.process.wait()
         finally:
             if os.path.exists(tmpfile_path):
                 os.remove(tmpfile_path)
             self.file_done += 1
     self.all_done = True
开发者ID:dikei,项目名称:mkv10b28b,代码行数:37,代码来源:file_collection.py

示例6: start

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
    def start(self):
        """
        запустить дочерний процесс консоли
        self.env - переоперделенные переменные окружения
        read_output_thread - поток читатель из std_out
        check_idle_thread - поток, проверяет активное ли соединение,
                            JavaScript делает переодически запросы к консоли для получить новые буквы ответа,
                            и если давно небыло опроса, то пора выходить
        """
        self.process = subprocess.Popen(
            'cmd.exe',
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            env=self.env,
            bufsize=1,
            cwd=self.physical_path
        )

        self.stdout_reader = OutputReader(self.process.stdout)
        self.stderr_reader = OutputReader(self.process.stderr)

        read_output_thread = Thread(target=self.read_output)
        read_output_thread.daemon = True
        read_output_thread.start()

        check_idle_thread = Thread(target=self.check_idle_thread)
        check_idle_thread.daemon = True
        check_idle_thread.start()
开发者ID:perldev,项目名称:zoo,代码行数:31,代码来源:console.py

示例7: _setup_vsim_process

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
  def _setup_vsim_process(self):
    print('\n' + color.success('*** Starting Modelsim ***'))
    env = { 'MGC_WD': os.getcwd(), 'PATH': os.environ['PATH'] }
    self.p = subp.Popen(['vsim',  '-c', '-l', self.log_file], env=env, stdin=subp.PIPE, stderr=subp.PIPE, stdout=subp.PIPE)

    self.outq = queue.Queue()
    self.errq = queue.Queue()

    out_thread = Thread(target=enqueue_pipe, args=(self.p.stdout, self.outq))
    err_thread = Thread(target=enqueue_pipe, args=(self.p.stderr, self.errq))
    out_thread.daemon = True
    err_thread.daemon = True
    out_thread.start()
    err_thread.start()

    # Keep the process from dying on an elaboration error
    self.p.stdin.write('onElabError resume\n')

    # Define a dummy sentinel proc
    self.p.stdin.write('proc sentinel {} {}\n')
    self.p.stdin.flush()

    # Wait for Modelsim to start and process our commands
    while True:
      out = get_output(self.outq)
      if 'sentinel' in out: break
开发者ID:carlosFPGA,项目名称:vhdl-extras,代码行数:28,代码来源:modelsim.py

示例8: successAction

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
def successAction(request):
    target = request['target']
    if target == 'client':
        terminate = request['disconnect']
        if(terminate == "true"):
            terminateThreads()
            return
        connection = request['connection_type']
        if(connection == "ssh"):
            print("opening terminal!")
            command = "ssh -v "+getpass.getuser()+"@localhost -p "+request['local_port']
            tunnels_on_select = Thread(target=startSSH, args=[command])
            tunnels_on_select.daemon = True
            tunnels_on_select.start()
            addThreadsRunning(tunnels_on_select)
        elif(connection == "web"):
            print("opening browser!")
            url = "http://localhost:3000"
            tunnels_on_select = Thread(target=startWEB, args=[url])
            tunnels_on_select.daemon = True
            tunnels_on_select.start()
            addThreadsRunning(tunnels_on_select)
        elif(connection == "vnc"):
            print("opening vnc!")
            port = request['local_port']
            tunnels_on_select = Thread(target=startVNC, args=[port])
            tunnels_on_select.daemon = True
            tunnels_on_select.start()
            addThreadsRunning(tunnels_on_select)
    elif target == 'tunneler':
        successResponse = request['messageToClient']
        pubSubClient.publish(routing_key=routingKey, body=bytes(json.dumps(successResponse), 'utf-8'))
开发者ID:cruiz1391,项目名称:Addigy4,代码行数:34,代码来源:Main.py

示例9: runProcess

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
def runProcess(commandline):
  """
  Run a process
  :param commandline: command line 
  :return:the return code
  """
  global finished
  debug ("Executing : %s" % commandline)
  exe = subprocess.Popen(commandline,
                         stdin=None,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=False,
                         bufsize=1, 
                         close_fds=ON_POSIX)

  t = Thread(target=print_output, args=("stdout", exe.stdout, False))
  t.daemon = True 
  t.start()
  t2 = Thread(target=print_output, args=("stderr", exe.stderr, True))
  t2.daemon = True 
  t2.start()

  debug("Waiting for completion")
  while exe.poll() is None:
    # process is running; grab output and echo every line
    time.sleep(1)
  debug("completed with exit code : %d" % exe.returncode)
  finished = True
  t.join()
  t2.join()
  return exe.returncode
开发者ID:Altiscale,项目名称:incubator-slider,代码行数:34,代码来源:slider.py

示例10: run

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
	def run(self,job, override_requirements=False, run_local = False):
		if type(self.project) == bool:
			raise Exception("No Project selected")
		if type(self.project.session) == bool:
			raise Exception("No Session selected")
		if len(self.processes) > self.max_threads:
			raise Exception("Too many jobs running.")
		if job.can_run() or override_requirements:
			if run_local:
				t = Thread(target = job.run)
				t.daemon = True # thread dies with the program
				t.start()
				self.job_threads.append(t)
			else:
				start_line = copy(self.run_prefixes)
				start_line.extend([self.project.folder, self.project.session.path, str(job.job_number)])
				self.processes.append(subprocess.Popen(start_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE))
				start_line = " ".join(start_line)
				self.process_jobs.append(job)
				job.process = "pid:" + str(self.processes[-1].pid)
				job.set_status("starting...")
				q = Queue()
				t = Thread(target=enqueue_output, args=(self.processes[-1].stdout, q))
				self.process_queue.append(q)
				self.process_thread.append(t)
				self.process_out.append(start_line+"\n")
				t.daemon = True # thread dies with the program
				t.start()
		else:
			raise Exception("Dependencies not satisfied")
开发者ID:jahuth,项目名称:ni,代码行数:32,代码来源:frontend.py

示例11: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
   def __init__(self, server_address, server_key, client_cert_prefix):
      self.context = zmq.Context.instance()

      # Load client private & public keys
      pub, sec = common.get_keys(client_cert_prefix)

      # Set up socket and connect to server
      self.server_socket = common.create_socket(self.context,
         zmq.DEALER,
         sec,
         pub,
         server_key);
      self.server_socket.connect(server_address)

      # Set up queue to push requests to
      request_queue = Queue()

      # List of reply listeners
      self.reply_listeners = []

      # Set up thread to delegate messages
      message_delegate = Thread(target=self.delegate_messages,\
         args=(self.server_socket, request_queue, self.reply_listeners))
      message_delegate.daemon = True
      message_delegate.start()

      # Set up thread to handle requests
      request_handler = Thread(target=self.reply_to_requests,\
         args=(request_queue, self.server_socket))
      request_handler.daemon = True
      request_handler.start()

      self.state = STATE_READY
开发者ID:wpharris92,项目名称:panorama,代码行数:35,代码来源:panorama.py

示例12: main

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
def main():
	parser = ArgumentParser(description='Multithreaded cat. Reads stdin and writes to stdout in parallel.')
	args = parser.parse_args()  # ignored at the moment.

	sin_fd = sys.stdin.fileno()
	sout = open(sys.stdout.fileno(), "wb", buffering=0, closefd=False)
	read_max_size = 1000000

	def read():
		# This has the behavior which we actually want:
		#  - If there are <= read_max_size bytes available, it will return those immediately,
		#    i.e. it will not block to wait until read_max_size bytes are available.
		#  - If there are 0 bytes available, it will block and wait until some bytes are available.
		v = os.read(sin_fd, read_max_size)
		return v or None
	def write(v):
		sout.write(v)
		sout.flush()

	pipe = Pipe()
	pipe.read = read
	pipe.write = write
	reader = Thread(name="reader", target=pipe.reader_loop)
	writer = Thread(name="writer", target=pipe.writer_loop)
	reader.daemon = True
	writer.daemon = True
	reader.start()
	writer.start()
	try:
		reader.join()
		writer.join()
	except KeyboardInterrupt:
		pass
开发者ID:albertz,项目名称:system-tools,代码行数:35,代码来源:mt-cat.py

示例13: start

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
	def start(self, shell_command):
		"""Start a command running in the sandbox"""
		shell_command = "docker run -v /var/www/nycsl/problems/workers/workingPath:/var/www/nycsl/problems/workers/workingPath --privileged=true virtual_machine sh -c \'" + shell_command + "\'"
		print("Shell command")
		print(shell_command)
		if self.is_alive:
			raise SandboxError("Tried to run command with one in progress.")
		working_directory = self.working_directory
		self.child_queue = Queue()
		shell_command = shlex.split(shell_command.replace('\\','/'))
		try:
			self.command_process = subprocess.Popen(shell_command,
													stdin=subprocess.PIPE,
													stdout=subprocess.PIPE,
													stderr=subprocess.PIPE,
													universal_newlines=True,
													cwd=working_directory)
		except OSError:
			print("There was an error")
			raise SandboxError('Failed to start {0}'.format(shell_command))
		self._is_alive = True
		stdout_monitor = Thread(target=_monitor_file,
								args=(self.command_process.stdout, self.stdout_queue))
		stdout_monitor.daemon = True
		stdout_monitor.start()
		stderr_monitor = Thread(target=_monitor_file,
								args=(self.command_process.stderr, self.stderr_queue))
		stderr_monitor.daemon = True
		stderr_monitor.start()
		Thread(target=self._child_writer).start()
开发者ID:HMProgrammingClub,项目名称:NYCSL,代码行数:32,代码来源:sandbox.py

示例14: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
    def __init__(self):
        self.p = Popen(["nice", "-n", "15", "avconv", "-i", "-",
                        "-probesize", "2048", "-flags", "low_delay", "-f",
                        "rawvideo", "-pix_fmt", 'rgb24', "-"],
                       stdin=PIPE, stdout=PIPE, stderr=open('/home/supun/error.txt', 'w'),
                       bufsize=0, preexec_fn=set_death_signal_int)
        t = Thread(target=self.enqueue_output, args=(self.p.stdout, (360, 640)))
        t.daemon = True
        t.start()

        self.frame_queue = Queue.Queue()

        self.time_queue = Queue.Queue()
        self.local_time_queue = Queue.Queue()

        # counting the tuples emitted
        self.emit_count = 0
        # frames received
        self.tuple_count = 0
        # weather we have removed the times from the time queue
        self.time_removed = 0
        # used to keep the difference between frames recieved and messages emitted
        self.diff = []

        # the control modules
        self.tracking = Tracking.Tracking()
        self.planing = Planning.Planning()

        send_thread = Thread(target=self.emit_message)
        send_thread.daemon = True
        send_thread.start()
开发者ID:applyhhj,项目名称:iotrobots,代码行数:33,代码来源:DroneFrameProcessBolt.py

示例15: __init__

# 需要导入模块: from threading import Thread [as 别名]
# 或者: from threading.Thread import daemon [as 别名]
   def __init__(self, socket_map, mav_iface, send_interval, dispatcher):
      Bridge.__init__(self, socket_map, mav_iface, send_interval)
      self.dead = False
      recv_thread = Thread(target = self._receive)
      recv_thread.daemon = True
      send_thread = Thread(target = self._send)
      send_thread.daemon = True
      self.dispatcher = dispatcher
      self.auto_mode_flags = MAV_MODE_FLAG_SAFETY_ARMED \
         | MAV_MODE_FLAG_MANUAL_INPUT_ENABLED \
         | MAV_MODE_FLAG_STABILIZE_ENABLED \
         | MAV_MODE_FLAG_GUIDED_ENABLED \
         | MAV_MODE_FLAG_AUTO_ENABLED

      Bridge.__init__(self, socket_map, mav_iface, send_interval)
      self.csb = ControlSensorBits()
      self.sensors_present = self.csb.bits(['GYRO_3D', 'ACC_3D', 'MAG_3D',
         'PRESSURE_ABS', 'GPS', 'ANGLE_RATE_CONTROL', 'ATTITUDE_CTRL',
         'YAW_CTRL', 'ALTITUDE_CTRL', 'XY_CTRL', 'MOTOR_CTRL'])
      self.sensors_enabled = self.sensors_present
      self.sensors_health = self.sensors_present
      self._load_reader = LoadReader()
      self._power_reader = PowerReader(socket_map['power_mon'])
      recv_thread.start()
      send_thread.start()
      self._load_reader.start()
      self._power_reader.start()
      self._power_reader.wait_data()
开发者ID:Aerobota,项目名称:PenguPilot,代码行数:30,代码来源:core_bridge.py


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