0

I've coded a Discord bot in Python. I have it hosted on a server that I use PuTTy to SSH into. Closing that terminal will obviously result in the bot ceasing to work. Does Python have a process management system that will allow me to keep a Python script running?

I'm running centOS.

Craig
  • 563
  • 1
  • 6
  • 18
  • 1
    What operating system is the server running? – Alex Hall May 24 '18 at 23:21
  • 1
    This is more of a ssh question then a python question, you can use nohup – fuzzycuffs May 24 '18 at 23:21
  • [Relevant.](https://pypi.org/project/python-daemon/) – user2357112 May 24 '18 at 23:22
  • If the server is running Linux, you can use nohup. `nohup python myScript.py &` – khushhall May 24 '18 at 23:23
  • Or start your bot in a tmux pane and then attach to that pane when you ssh into the server. – Patrick Haugh May 24 '18 at 23:28
  • If you actually need to do this from within Python, you’re basically asking how to write a daemon. Assuming you’re on Unix/Linux, look for the Python daemon library on PyPI. But usually you don’t need this; you just need `nohup`, and you can find more details more easily on Super User, Server Fault, Unix, AskDifferent, AskUbuntu, etc. than Stack Overflow, because it’s more of a sysadmin question than a programming one. – abarnert May 24 '18 at 23:30

1 Answers1

0

It depends about how much experience you have programming in python. For example you could use daemonize (which I personally prefer). And this is the simplest example available (from the daemonize documentation)

from time import sleep
from daemonize import Daemonize

pid = "/tmp/test.pid"


def main():
    while True:
        sleep(5)

daemon = Daemonize(app="test_app", pid=pid, action=main)
daemon.start()

Another way to keep your script running, it could be install screen. Execute screen before executing your script and then detach the session using "Ctrl+a"+"d"

  • Thanks, `screen` seems to be a pretty good solution. Do you know if there's any way I can utilize screen so that this same Python script re-launches if the server happens to restart? – Craig May 25 '18 at 00:00
  • The easiest way to achieve this is to append the path of your script into /etc/rc.local – Gioachino Bartolotta May 25 '18 at 09:12