Skip to content

Instantly share code, notes, and snippets.

@marcuscaisey
Created April 11, 2019 00:07
Show Gist options
  • Save marcuscaisey/6b5c4a264230143e1e93a01c6b36fdcd to your computer and use it in GitHub Desktop.
Save marcuscaisey/6b5c4a264230143e1e93a01c6b36fdcd to your computer and use it in GitHub Desktop.
Basic script which allows for start/stopping with only one instance allowed to be running at a time.
#!/usr/local/bin/python3
import os
import signal
import time
import sys
PID_FILENAME = __file__.split("/")[-1] + ".pid"
def main():
stop = False
def exit_handler(signum, frame):
nonlocal stop
stop = True
signal.signal(signal.SIGTERM, exit_handler)
signal.signal(signal.SIGINT, exit_handler)
try:
with open(PID_FILENAME, "x") as f:
f.write(str(os.getpid()))
except FileExistsError:
print("main already running")
sys.exit(1)
while not stop:
print("running main:", end=" ", flush=True)
for i in range(5):
print(i + 1, end=" ", flush=True)
time.sleep(1)
print()
os.unlink(PID_FILENAME)
def stop():
try:
with open(PID_FILENAME) as f:
pid = int(f.read())
except FileNotFoundError:
print("main not running")
sys.exit(1)
os.kill(pid, signal.SIGTERM)
try:
command = sys.argv[1]
except IndexError:
print("no command")
sys.exit(1)
if command == "start":
main()
elif command == "stop":
stop()
else:
print("invalid command")
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment