1

Got a Django app that has users going through a setup wizard. After the wizard, the app needs to restart for it to pick the necessary settings.

The app is run on Ubuntu 18.04 and monitored using supervisord.

Ideally am looking to call systemctl restart supervisord.service from the Django app itself.

So I've tried

import subprocess
subprocess.run("systemctl restart supervisord.service")

However, this fails with the error:

FileNotFoundError [Errno 2] No such file or directory: 'systemctl restart supervisord.service': 'systemctl restart supervisord.service'

There is this question here on SO but that is an older question and the answers there are relying on os.* while as of this posting subprocess seems to be the preferred way or accessing OS function

lukik
  • 3,919
  • 6
  • 46
  • 89
  • Possible duplicate of [Restart python-script from within itself](https://stackoverflow.com/questions/11329917/restart-python-script-from-within-itself) – Mike Scotty Aug 04 '19 at 14:55
  • Its related but recent text seems to indicate that _subprocess.run_ is the _new_ preferred way?.. – lukik Aug 04 '19 at 15:17

2 Answers2

1

Seen my error. The command should be run as:

subprocess.run(["systemctl", "restart", "supervisor.service"])

source: http://queirozf.com/entries/python-3-subprocess-examples

lukik
  • 3,919
  • 6
  • 46
  • 89
0

For more cleaner way to start your own python program would be:-

import os
import sys
import psutil
import logging

def restart_program():
    """Restarts the current program, with file objects and descriptors
       cleanup
    """

    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

    python = sys.executable
    os.execl(python, python, *sys.argv)
  • Thanks. Will try it out. Would you mind explaining why its cleaner than using subprocess? – lukik Aug 05 '19 at 03:39