4

I have a python script that constantly runs (it has an infinite loop), but I want it to be able to still accept input while running. It will run in the background and then at any time I want to be able to type

scriptname stop

and stop it (or something like that). That way it can call a shutdown method to save information and quit.

Currently it runs in the foreground in the terminal, and can't be stopped by a keyboard interrupt, so the only way to kill it is to close the terminal or kill python.

How can I do something like this?

mrobinson7627
  • 298
  • 1
  • 4
  • 13

2 Answers2

3

Use supervisord. It exists to manage processes, and provides a command interface to start and stop them.

When supervisor kills a process, it sends SIGTERM (or any other signal you choose). So, to shutdown cleanly, you need to handle that signal.

See this question on how to handle SIGTERM: Python - Trap all signals

Processes can still listen on their own pipes for input, and send output that way.

Community
  • 1
  • 1
Marcin
  • 48,559
  • 18
  • 128
  • 201
  • Is there any way I can use supervisord to send information into the script? Like in order to trigger the shutdown method? I want to make sure that it's not in the middle of doing something when it gets shut down. – mrobinson7627 Nov 20 '12 at 18:05
0

If you are in Windows then You are at right point...

Just Rename your file: script.py to script.pyw and Use It Normally.
Your Script will run in background.

To close that script:
Go to Task Manager , click on Process Tab , look out for python , End Task.

If You need more information I am Ready to Provide to you...
I am Not Sure About Linux or Ubuntu.
Thanks.