From 150d069dfb614fb193b0976e35d632fe2444d7a3 Mon Sep 17 00:00:00 2001 From: nemunaire Date: Mon, 18 May 2015 07:36:49 +0200 Subject: [PATCH] New CLI argument: --pidfile, path to store the daemon PID --- nemubot/__init__.py | 5 +++++ nemubot/__main__.py | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/nemubot/__init__.py b/nemubot/__init__.py index 4a2e789..668dd6c 100644 --- a/nemubot/__init__.py +++ b/nemubot/__init__.py @@ -38,6 +38,11 @@ def requires_version(min=None, max=None): "but this is nemubot v%s." % (str(max), __version__)) +def attach(pid): + print("TODO, attach to %d" % pid) + return 0 + + def daemonize(): """Detach the running process to run as a daemon """ diff --git a/nemubot/__main__.py b/nemubot/__main__.py index 114b83c..7db715b 100644 --- a/nemubot/__main__.py +++ b/nemubot/__main__.py @@ -40,6 +40,9 @@ def main(): parser.add_argument("-d", "--debug", action="store_true", help="don't deamonize, keep in foreground") + parser.add_argument("-P", "--pidfile", default="./nemubot.pid", + help="Path to the file where store PID") + parser.add_argument("-l", "--logfile", default="./nemubot.log", help="Path to store logs") @@ -62,15 +65,33 @@ def main(): # Resolve relatives paths args.data_path = os.path.abspath(os.path.expanduser(args.data_path)) + args.pidfile = os.path.abspath(os.path.expanduser(args.pidfile)) args.logfile = os.path.abspath(os.path.expanduser(args.logfile)) args.files = [ x for x in map(os.path.abspath, args.files)] args.modules_path = [ x for x in map(os.path.abspath, args.modules_path)] + # Check if an instance is already launched + if args.pidfile is not None and os.path.isfile(args.pidfile): + with open(args.pidfile, "r") as f: + pid = int(f.readline()) + try: + os.kill(pid, 0) + except OSError: + pass + else: + from nemubot import attach + sys.exit(attach(pid)) + # Daemonize if not args.debug: from nemubot import daemonize daemonize() + # Store PID to pidfile + if args.pidfile is not None: + with open(args.pidfile, "w+") as f: + f.write(str(os.getpid())) + # Setup loggin interface import logging logger = logging.getLogger("nemubot")