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


Python daemonize.Daemonize类代码示例

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


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

示例1: run_maintenance

	def run_maintenance(self):
		"""
			The method runs a maintenance process on the target postgresql database specified in the given source.
		"""
		maintenance_pid = os.path.expanduser('%s/%s_maintenance.pid' % (self.config["pid_dir"],self.args.source))
		if self.args.source == "*":
			print("You must specify a source name with the argument --source")
		else:
			if self.args.debug:
				self.pg_engine.run_maintenance()
			else:
				if self.config["log_dest"]  == 'stdout':
					foreground = True
				else:
					self.logger.info("Starting the maintenance on the source %s" % (self.args.source, ))
					foreground = False
					print("Starting the maintenance process for source %s" % (self.args.source))
					keep_fds = [self.logger_fds]
					
					app_name = "%s_maintenance" % self.args.source
					maintenance_daemon = Daemonize(app=app_name, pid=maintenance_pid, action=self.pg_engine.run_maintenance, foreground=foreground , keep_fds=keep_fds)
					try:
						maintenance_daemon.start()
					except:
						print("The  maintenance process is already started. Aborting the command.")
开发者ID:the4thdoctor,项目名称:pg_chameleon,代码行数:25,代码来源:global_lib.py

示例2: setup

def setup():
    parser = argparse.ArgumentParser()
    parser.add_argument("directory")
    parser.add_argument("-p", "--port", dest="port", type=int, default=8080)
    parser.add_argument('-P', "--pid-file", dest="pid", default="web.pid")
    args = parser.parse_args()

    # Get absolute path to directory to serve, as daemonize changes to '/'
    os.chdir(args.directory)
    dr = os.getcwd()

    httpd = BaseHTTPServer.HTTPServer(
        ('', args.port),
        SimpleHTTPRequestHandlerWithPOST
    )

    def run():
        os.chdir(dr)
        httpd.serve_forever()

    daemon = Daemonize(
            app="synapse-webclient",
            pid=args.pid,
            action=run,
            auto_close_fds=False,
        )

    daemon.start()
开发者ID:0-T-0,项目名称:synapse,代码行数:28,代码来源:webserver.py

示例3: __init__

 def __init__(self, app, pid, action, keep_fds=None, foreground=False):
         Daemonize.__init__(
             self, app, pid, action,
             keep_fds=keep_fds,
             foreground=foreground)
         signal.signal(signal.SIGINT, self.sigterm)
         signal.signal(signal.SIGTERM, self.sigterm)
开发者ID:BronzeCrab,项目名称:sound_service_task,代码行数:7,代码来源:daemon.py

示例4: sigterm

 def sigterm(self, signum, frame):
     now = datetime.now().strftime('%Y.%m.%d %H:%M')
     if signum == 15:
         logger.debug("{} - SIGTERM, завершение работы".format(now))
     if signum == 2:
         logger.debug("{} - SIGINT, завершение работы".format(now))
     Daemonize.sigterm(self, signum, frame)
开发者ID:BronzeCrab,项目名称:sound_service_task,代码行数:7,代码来源:daemon.py

示例5: main

def main():
    parser = argparse.ArgumentParser(description='cstar_perf_notifications')
    parser.add_argument('-F', '--foreground', dest='foreground', 
                        action='store_true', help='Run in the foreground instead of daemonizing')
    parser.add_argument('--pid', default="/tmp/cstar_perf_notifications.pid", 
                        help='PID file for daemon', dest='pid')
    parser.add_argument('-l', '--log', default='/tmp/cstar_perf_notifications.log',
                        help='File to log to', dest='logfile')
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='Print log messages', dest='verbose')
    args = parser.parse_args()

    log.setLevel(logging.DEBUG)
    log.propagate = False
    fh = logging.FileHandler(args.logfile, "a")
    formatter = logging.Formatter("%(levelname)s:%(funcName)s:%(asctime) -8s %(message)s")
    fh.setFormatter(formatter)
    fh.setLevel(logging.DEBUG)
    log.addHandler(fh)
    if args.verbose:
        sh = logging.StreamHandler()
        sh.setFormatter(formatter)
        sh.setLevel(logging.DEBUG)
        log.addHandler(sh)
    keep_fds = [fh.stream.fileno()]


    if args.foreground:
        multi_service()
    else:
        daemon = Daemonize(app="notifications", pid=args.pid, action=multi_service, keep_fds=keep_fds)
        daemon.start()
开发者ID:TheRealFalcon,项目名称:cstar_perf,代码行数:32,代码来源:notifications.py

示例6: setup

def setup():
    config = HomeServerConfig.load_config(
        "Synapse Homeserver",
        sys.argv[1:],
        generate_section="Homeserver"
    )

    config.setup_logging()

    logger.info("Server hostname: %s", config.server_name)

    if re.search(":[0-9]+$", config.server_name):
        domain_with_port = config.server_name
    else:
        domain_with_port = "%s:%s" % (config.server_name, config.bind_port)

    tls_context_factory = context_factory.ServerContextFactory(config)

    hs = SynapseHomeServer(
        config.server_name,
        domain_with_port=domain_with_port,
        upload_dir=os.path.abspath("uploads"),
        db_name=config.database_path,
        tls_context_factory=tls_context_factory,
        config=config,
        content_addr=config.content_addr,
    )

    hs.register_servlets()

    hs.create_resource_tree(
        web_client=config.webclient,
        redirect_root_to_web_client=True,
    )
    hs.start_listening(config.bind_port, config.unsecure_port)

    hs.get_db_pool()

    if config.manhole:
        f = twisted.manhole.telnet.ShellFactory()
        f.username = "matrix"
        f.password = "rabbithole"
        f.namespace['hs'] = hs
        reactor.listenTCP(config.manhole, f, interface='127.0.0.1')

    if config.daemonize:
        print config.pid_file
        daemon = Daemonize(
            app="synapse-homeserver",
            pid=config.pid_file,
            action=run,
            auto_close_fds=False,
            verbose=True,
            logger=logger,
        )

        daemon.start()
    else:
        run()
开发者ID:martindale,项目名称:synapse,代码行数:59,代码来源:homeserver.py

示例7: start_reactor

def start_reactor(
        appname,
        soft_file_limit,
        gc_thresholds,
        pid_file,
        daemonize,
        cpu_affinity,
        logger,
):
    """ Run the reactor in the main process

    Daemonizes if necessary, and then configures some resources, before starting
    the reactor

    Args:
        appname (str): application name which will be sent to syslog
        soft_file_limit (int):
        gc_thresholds:
        pid_file (str): name of pid file to write to if daemonize is True
        daemonize (bool): true to run the reactor in a background process
        cpu_affinity (int|None): cpu affinity mask
        logger (logging.Logger): logger instance to pass to Daemonize
    """

    def run():
        # make sure that we run the reactor with the sentinel log context,
        # otherwise other PreserveLoggingContext instances will get confused
        # and complain when they see the logcontext arbitrarily swapping
        # between the sentinel and `run` logcontexts.
        with PreserveLoggingContext():
            logger.info("Running")
            if cpu_affinity is not None:
                if not affinity:
                    quit_with_error(
                        "Missing package 'affinity' required for cpu_affinity\n"
                        "option\n\n"
                        "Install by running:\n\n"
                        "   pip install affinity\n\n"
                    )
                logger.info("Setting CPU affinity to %s" % cpu_affinity)
                affinity.set_process_affinity_mask(0, cpu_affinity)
            change_resource_limit(soft_file_limit)
            if gc_thresholds:
                gc.set_threshold(*gc_thresholds)
            reactor.run()

    if daemonize:
        daemon = Daemonize(
            app=appname,
            pid=pid_file,
            action=run,
            auto_close_fds=False,
            verbose=True,
            logger=logger,
        )
        daemon.start()
    else:
        run()
开发者ID:rubo77,项目名称:synapse,代码行数:58,代码来源:_base.py

示例8: start

def start(config_options):
    try:
        config = HomeServerConfig.load_config(
            "Synapse federation reader", config_options
        )
    except ConfigError as e:
        sys.stderr.write("\n" + e.message + "\n")
        sys.exit(1)

    assert config.worker_app == "synapse.app.federation_reader"

    setup_logging(config.worker_log_config, config.worker_log_file)

    database_engine = create_engine(config.database_config)

    tls_server_context_factory = context_factory.ServerContextFactory(config)

    ss = FederationReaderServer(
        config.server_name,
        db_config=config.database_config,
        tls_server_context_factory=tls_server_context_factory,
        config=config,
        version_string="Synapse/" + get_version_string(synapse),
        database_engine=database_engine,
    )

    ss.setup()
    ss.get_handlers()
    ss.start_listening(config.worker_listeners)

    def run():
        with LoggingContext("run"):
            logger.info("Running")
            change_resource_limit(config.soft_file_limit)
            if config.gc_thresholds:
                gc.set_threshold(*config.gc_thresholds)
            reactor.run()

    def start():
        ss.get_state_handler().start_caching()
        ss.get_datastore().start_profiling()
        ss.replicate()

    reactor.callWhenRunning(start)

    if config.worker_daemonize:
        daemon = Daemonize(
            app="synapse-federation-reader",
            pid=config.worker_pid_file,
            action=run,
            auto_close_fds=False,
            verbose=True,
            logger=logger,
        )
        daemon.start()
    else:
        run()
开发者ID:mebjas,项目名称:synapse,代码行数:57,代码来源:federation_reader.py

示例9: daemonize

def daemonize(pidfile):
    try:
        import traceback
        from daemonize import Daemonize
        daemon = Daemonize(app='pynab', pid=pidfile, action=main)
        daemon.start()
    except SystemExit:
        raise
    except:
        log.critical(traceback.format_exc())
开发者ID:tbetton,项目名称:pynab,代码行数:10,代码来源:api.py

示例10: start

def start(configfile):
    _load_config(configfile)
    os.environ["UPD89_DATADIR"] = _config.getDataDir()

    newpid = os.fork()
    if newpid == 0:
        import websrv
        websrv.start(_config)
    else:
        daemon = Daemonize(app="test_app", pid=_pid, action=main,
                           keep_fds=_log.getKeepfds())
        daemon.start()
开发者ID:upd89,项目名称:agent,代码行数:12,代码来源:agent.py

示例11: main

def main():
    parser, opts = parseopt()

    if path.exists(opts.socket):
        print("+ socket file {} already exists".format(opts.socket))
        exit(1)

    if opts.daemonize:
        print("+ daemonizing - pid file {}".format(opts.pidfile))
        daemon = Daemonize(app="module_launcher", pid=opts.pidfile, action=lambda: _main(opts))
        daemon.start()
    else:
        _main(opts)
开发者ID:gvalkov,项目名称:python-module-launcher,代码行数:13,代码来源:modulelauncher.py

示例12: main

def main(argv=None):

    logger.setLevel(CONF.log_level)
    formatter = logging.Formatter(CONF.log_format)
    handler = logging.FileHandler(CONF.log_file)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    daemon = Daemonize(app="Downtimer",
                       pid=CONF.pid_file,
                       action=downtimer_starter,
                       logger=logger,
                       keep_fds=[handler.stream.fileno()])
    daemon.start()
开发者ID:dstepanenko,项目名称:downtimer,代码行数:14,代码来源:main.py

示例13: startApp

def startApp(ourWsgiApp):
  global runWsgiApp
  runWsgiApp = ourWsgiApp

  if runInForeGround:
    runApp()
    return

  ourPidfile = runningConfig.server.pidfile

  ourDaemon = Daemonize(app = 'wsgiApp', 
                        pid = ourPidfile,
                        action = runApp,
                        verbose = True)
  ourDaemon.start()
开发者ID:gknight007,项目名称:falcons_nest,代码行数:15,代码来源:command_line.py

示例14: daemonize

def daemonize(pidfile):
    try:
        import traceback
        from daemonize import Daemonize

        fds = []
        if log_descriptor:
            fds = [log_descriptor]

        daemon = Daemonize(app='pynab', pid=pidfile, action=main, keep_fds=fds)
        daemon.start()
    except SystemExit:
        raise
    except:
        log.critical(traceback.format_exc())
开发者ID:tbetton,项目名称:pynab,代码行数:15,代码来源:start.py

示例15: run_server

def run_server():
    parser = ArgumentParser()
    parser.add_argument('command', choices=['START', 'STOP', 'RESTART'])

    parser.add_argument('--port', type=int, default=default_port,
                        help='the port the server will use (default: {0})'.format(default_port))

    parser.add_argument('--taskqueue', type=str, default=default_taskqueue,
                        help='hostname of the taskqueue (default: {0})'.format(default_taskqueue))

    parser.add_argument('--triplestore', type=str, default=default_triplestore,
                        help='hostname of the triplestore (default: {0})'.format(default_triplestore))

    parser.add_argument('--background', action="store_true",
                        help='when provided, the server will run in the background')

    arguments = parser.parse_args()

    def args_run():
        run(arguments.port, arguments.taskqueue, arguments.triplestore)

    pidfile = '/var/run/sos-server.pid'
    command = arguments.command.upper()
    if command != 'START':
        from os import kill
        from signal import SIGTERM
        from errno import EPERM

        # stop the server
        pid = int(open(pidfile).read())
        try:
            kill(pid, SIGTERM)
            print('The SPARQL over SMS server has been stopped.')
        except OSError as e:
            if e.errno == EPERM:
                exit(1)

        if command == 'STOP':
            exit(0)

    if arguments.background:
        from daemonize import Daemonize

        daemon = Daemonize(app="sos-server", pid=pidfile, action=args_run)
        daemon.start()
    else:
        args_run()
开发者ID:onnovalkering,项目名称:sparql-over-sms,代码行数:47,代码来源:sos_server.py


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