1

This has been a two day struggle, and I am quite stuck.

TLDR: From within a Python shell (>>> "like this"), start a Python script that survives quit() and me@terminal:~$ exit.


I have tried:

  • various daemonizing functions that implement os.fork()
  • creating/calling a shell script with Popen and & appended
  • subprocess.Popen(["nohup", "command.py"]) in several forms

Toy Code - Python 3.6

class MyClass(threading.Thread):
    def __init__(self, filepath):
        super().__init__()
        self.filepath = filepath

    def run(self):
        import time
        i = 0
        while True:  # Count to 50 in a file forever
            if i > 50: i = 0
            with open(self.filepath, "a") as afile:
                afile.writelines("This is msg {}\n".format(i))
            i += 1
            time.sleep(1)

How can I run this Thread from within the Python shell in such a way that it doesn't die when I close my interpreter and close my SSH terminal?


Real Code Django-managed DB consumption of PubNub messages

See # TODO line, near center. The PNRunner class instances will be started and killed dynamically within the construct of a Django app, so I can't just start them at boot with a shell script.

what I actually want to do

PANDA Stack
  • 1,293
  • 2
  • 11
  • 30
  • `nohup python command.py &`? – Sean Pianka Jul 26 '18 at 22:23
  • @SeanPianka Unfortunately that didn't seem to work empirically. I'm not sure WHY, but c'est la vie. It's actually the first thing I looked at. – PANDA Stack Jul 26 '18 at 22:33
  • 1
    I believe this can be done with a double fork (https://stackoverflow.com/questions/881388/what-is-the-reason-for-performing-a-double-fork-when-creating-a-daemon). There is a python example here (https://gist.github.com/Ma233/dd1f2f93db5378a29a3d1848288f520e). – Ollin Boer Bohan Jul 26 '18 at 22:33
  • @OllinBoerBohan I think you are correct. I have tried a couple times and it seems I'm not skilled enough to make it actually work... I see the example there, so I will muddle through that for a time. – PANDA Stack Jul 26 '18 at 22:35
  • 1
    Per discussion in the linked thread, you can try just using https://pypi.org/project/python-daemon/ and see if that works – Ollin Boer Bohan Jul 26 '18 at 22:36
  • @OllinBoerBohan I clearly lack system knowledge here. The (nearly exact) implementation of `Daemon` I am working on calls `os.fork()`, but returns a non-zero PID and `sys.exit`s every time. Which kills the interpreter, and nothing is left running. So I am quite flummoxed. – PANDA Stack Jul 26 '18 at 23:47
  • This is now functional! Thank you. The breakthrough was in two simple realizations: First - `change MyClass to subclass Daemon, not Thread`. Second - `getting exit code 0 means it's working`. So I am grateful. Thank you. I will accept an answer posted here reflecting this if you want to post it. – PANDA Stack Jul 27 '18 at 00:25

0 Answers0