0

let me first start off saying sorry if this is duplicate. a link to the correct thread will be helpful, i just could not find what I was looking for with searching.

I have a python application that checks the status of different things in our network and then writes XML files. It has a constant loop that run through all the checks. Occasionally the application needs to be stopped or restarted to make a change. I don't want to quite the app or restart the app while it is writing a file or executing a task. What are some strategies I can use to terminate the main loop safely? Can I pass something to an object that is running something?

jspada
  • 481
  • 1
  • 6
  • 24
  • Use `flags`, for instance `quit = False` and honor that in critical places of the code. You can also catch signals https://docs.python.org/3/library/signal.html – Torxed Nov 18 '15 at 17:18

2 Answers2

1

In addition to suggestionsabout signals(https://docs.python.org/3/library/signal.html) @Torxed mentioned in his comment, you can also pass some data to program and verify is it set on every loop iteration(I mean pass to stdin, see comments here: How do I check if stdin has some data?)

Another way is to create a file and check if it exists on every iteration. If if doesn't - stop the application.

Community
  • 1
  • 1
Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54
0

A common usage is to put a check point in the loop. At the simplest level, you just test if a particular file exist and exit loop if it does:

stopfile = '.stop'

while True:
    # check if we are required to stop
    if os.path.exists(stopfile):
        print("Stopping because %s exists" % (stopfile,))
        break
    # real stuff

In more complex scenarii, you can use any interprocess tool, for example a socket or signals and test it the same way in your loop

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252