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


Python DaemonContext.close方法代码示例

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


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

示例1: close

# 需要导入模块: from daemon import DaemonContext [as 别名]
# 或者: from daemon.DaemonContext import close [as 别名]
    def close(self):
        # We might get called more than once, or before worker exists
        if self.is_open and self.worker and self.worker.is_alive():
            self.logger.info('Stopping worker...')
            self.worker.should_stop = True
            self.worker.join(5)  # Wait up to 5 seconds
            if self.worker.is_alive():
                self.logger.warn(
                    'Error stopping worker. Shutting down uncleanly.'
                )
            self.logger.info('Stopped.')

        DaemonContext.close(self)
开发者ID:Apsu,项目名称:rpcdaemon,代码行数:15,代码来源:__init__.py

示例2: start

# 需要导入模块: from daemon import DaemonContext [as 别名]
# 或者: from daemon.DaemonContext import close [as 别名]
	def start(self, detachProcess=True):
		pidFile = TimeoutPIDLockFile(self._pidFile)

		context = DaemonContext(
			working_directory=self._runDir,
			umask=0o002,
			pidfile=pidFile,
			detach_process=detachProcess,
		)

		context.signal_map = {
			signal.SIGTERM: 'terminate',
			signal.SIGHUP: 'terminate',
			signal.SIGUSR1: 'terminate',
		}

		if self._isRunningAndBreak(pidFile):
			raise AlreadyRunning("PID file locked and process not stale")

		self._context = context
		try:
			context.open()
			self._setupLogging()
		except:
			if self.logger is None:
				self._setupLogging()
			self.logger.warn("Exception while entering context", exc_info=True)
			try:
				context.close()
			except:
				pass
			return

		try:
			self.run()
		except Exception as e:
			self.logger.error("Exception in run()", exc_info=e)
		finally:
			self.logger.debug("Shutting down daemon")
			self.shutdown()
			try:
				self._fHandler.close()
			except:
				pass
			try:
				context.close()
			except:
				pass
开发者ID:seoester,项目名称:vycodi,代码行数:50,代码来源:daemon.py

示例3: SerialDaemon

# 需要导入模块: from daemon import DaemonContext [as 别名]
# 或者: from daemon.DaemonContext import close [as 别名]
class SerialDaemon():
    """A wrapper class for Serial and DaemonContext with inet socket support.

    Creates a DaemonContext object and a Serial object using the passed
    arguments. Some arguments do not take effect after the daemon is started
    and hence can be altered anytime after initialization until it is started
    by calling <daemon>.start()

    Communication with the daemon is done on a port number specified during
    initialization (or anytime before start), defaulting to 57001. Data is
    decoded using the user specified encoding (default is UTF-8) and must be
    either exactly 'device', in which case the daemon will reply with the full
    path to the device file it is communicating with (serial_context.port),
    or it must be in the following format:
        <0-F><0-F0-F...0-F><data to be sent to device>
    where the first byte of data always signifies how many (base 16) bytes
    following it give the the number (base 16) of bytes that are to be read
    from device after the data is sent to it. 0 bytes are read if data[0] is
    0 or is not a valid hex number. <data[0] number of bytes> + 1 are always
    discarded from the beginning of data. For example:
        22F8921 sends 8921 to device and reads 2F (47) bytes of data
        X78192 sends 78192 to device and dos not read a reply
        3A2G9130 sends 9130 to device BUT does not read a reply since A2G is
            not a valid hex number. Note that these 3 bytes are still discarded

    This class does not inherit from either DaemonContext or Serial.
    The only export method is start() used to run the daemon.

    Accepted options for the constructor:

    name
        :Default: ``None``

        The name of the daemon, used for syslog and the default
        name of the pidfile and configuration files. Changes to this value
        after the daemon has started will only be reflected in syslog.

    config_file
        :Default: ``'/etc/<name>.conf'``

        Configuration file used to set some of the hereby listed parameters.
        All but name, daemon_context and serial_context are supported.
        Reloading of the configuration without restarting is done by sending
        SIGHUP to the daemon but please note that changes to pidfile_path,
        socket_path and log_file require restart to take effect.
        The format is as follows:
            <option_name> = <option value>
        Option names are case-INsensitive and ``_`` may be replaced by ``-``.
        Spaces around ``=`` are optional and have no effect.
        Option values may optionally be enclosed in either single or double
        quotes. # and any text following it on the line are ignored.

    log_file
        :Default: ``/tmp/<name>.log``

        Log file used to log exceptions during daemon run.

    pidfile_path
        :Default: ``'/var/run/<name>.pid'``

        Path to the pidfile. A pidfile lock is created and passed to
        DaemonContext. Alternatively, you may pass a pid lockfile directly by
        setting <daemon>.daemon_context.pidfile to the lockfile after
        initialization but before start. Changing either of them after the
        daemon is started requires a restart.

    socket_path
        :Default: ``'/var/run/<name>.socket'``

        Path for the unix daemon socket which the daemon will be listening on.
        Changing this after the daemon is started requires a restart. Also see
        documentation for serial.py.

    data_length
        :Default: ``1024``

        Number of bytes to be read from the socket. This MUST be at least the
        number of bytes that have been sent, otherwise the remainder is read
        afterwards and is confused for a new packet. See above for details on
        the data format.

    data_encoding
        :Default: ``'utf-8'``

        Valid encoding (accepted by the str.decode() and bytes() methods) for
        the data read from and sent to the socket.

    reply_length_strict
        :Default: ``False``

        If True daemon will not send data read from device unless the length
        matches the expected reply length given as part of the data sent over
        the socket. See above for details on the data format.

    daemon_context
        :Default: ``None``

        If this is not None, it must be a DaemonContext object and is used
        instead of creating a new one. All options relating to DaemoonContext
        are then ignored.
#.........这里部分代码省略.........
开发者ID:aayla-secura,项目名称:lfi-3751-control,代码行数:103,代码来源:seriald.py

示例4: get_dns

# 需要导入模块: from daemon import DaemonContext [as 别名]
# 或者: from daemon.DaemonContext import close [as 别名]
        while True:

            time.sleep(1)

            if i % REFRESH_DNS == 0:
                log.info('Refreshing the valid DNs.')
                dns = get_dns(options.dn_file)
                ssm.set_dns(dns)

                try:
                    log.info('Sending ping.')
                    ssm.send_ping()
                except NotConnectedException:
                    log.error('Connection lost.')
                    ssm.shutdown()
                    dc.close()
                    log.info("Waiting for 10 minutes before restarting...")
                    time.sleep(10 * 60)
                    log.info('Restarting SSM.')
                    dc.open()
                    ssm.startup()

            i += 1

    except SystemExit, e:
        log.info('Received the shutdown signal: %s', e)
        ssm.shutdown()
        dc.close()
    except Exception, e:
        log.error('Unexpected exception: %s', e)
        log.error('Exception type: %s', e.__class__)
开发者ID:gregcorbett,项目名称:ssm,代码行数:33,代码来源:receiver.py

示例5: main

# 需要导入模块: from daemon import DaemonContext [as 别名]
# 或者: from daemon.DaemonContext import close [as 别名]
def main():
    #  Logger
    _logger = logger.Logger('middleware')
    get_logger = _logger.getLogger()

    # Workaround for development
    modpath = os.path.realpath(os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        '..',
    ))
    if modpath not in sys.path:
        sys.path.insert(0, modpath)

    parser = argparse.ArgumentParser()
    parser.add_argument('restart', nargs='?')
    parser.add_argument('--foreground', '-f', action='store_true')
    parser.add_argument('--disable-loop-monitor', '-L', action='store_true')
    parser.add_argument('--plugins-dirs', '-p', action='append')
    parser.add_argument('--debug-level', default='DEBUG', choices=[
        'DEBUG',
        'INFO',
        'WARN',
        'ERROR',
    ])
    parser.add_argument('--log-handler', choices=[
        'console',
        'file',
    ])
    args = parser.parse_args()

    if args.log_handler:
        log_handlers = [args.log_handler]
    else:
        log_handlers = ['console' if args.foreground else 'file']

    pidpath = '/var/run/middlewared.pid'

    if args.restart:
        if os.path.exists(pidpath):
            with open(pidpath, 'r') as f:
                pid = int(f.read().strip())
            os.kill(pid, 15)

    if not args.foreground:
        _logger.configure_logging('file')
        daemonc = DaemonContext(
            pidfile=TimeoutPIDLockFile(pidpath),
            detach_process=True,
            stdout=logger.LoggerStream(get_logger),
            stderr=logger.LoggerStream(get_logger),
        )
        daemonc.open()
    elif 'file' in log_handlers:
        _logger.configure_logging('file')
        sys.stdout = logger.LoggerStream(get_logger)
        sys.stderr = logger.LoggerStream(get_logger)
    elif 'console' in log_handlers:
        _logger.configure_logging('console')
    else:
        _logger.configure_logging('file')

    setproctitle.setproctitle('middlewared')
    # Workaround to tell django to not set up logging on its own
    os.environ['MIDDLEWARED'] = str(os.getpid())

    Middleware(
        loop_monitor=not args.disable_loop_monitor,
        plugins_dirs=args.plugins_dirs,
    ).run()
    if not args.foreground:
        daemonc.close()
开发者ID:binzyw,项目名称:freenas,代码行数:73,代码来源:main.py


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