0

I have a simple function that polls a folder and loads a new file when one is detected:

raw = []

def poll_file(mydir, raw)
    while 1:
        after = dict([(f, None) for f in os.listdir(mydir)])
        added = [f for f in after if f not in before]

        # New File
        if added:
            raw.append(numpy.loadtxt(mydir + added[0]))

            # Set Trigger
            if raw[-1] > 5:
                trigger = 1

return trigger

In my main script, at some points in time, I will want to wait until trigger turns to '1', but during times I don't care what trigger is, I want my variable raw to continue to be appended with new data from the new files.

So, I have two questions.

  1. How do I start running a python function in the background?

  2. How do I setup trigger as a global variable that can be read in my main script and then reset to 0, like:

    while trigger != 1: # do nothing until trigger == 1 trigger = 0

  3. How do I stop the constant function in the background and save raw to a pickle file in the end? I assume I would set it as a global variable.

user1566200
  • 1,686
  • 2
  • 21
  • 41
  • 2. declare trigger as global if you want to assign it in your function. Otherwise the LEGB scope rule holds. – Pynchia Jun 04 '15 at 19:30
  • Where do I define the variable global - in my main script, or in the function I want to run in the background? – user1566200 Jun 04 '15 at 20:01
  • Have a look at this library: http://home.gna.org/py-notify/ – Pynchia Jun 04 '15 at 20:01
  • declare it global within the function (mind you on 99% of the cases, globals can and should be avoided). If you are using Python 3, you also have the option of using `nonlocal`, it depends on your design. See this: https://www.safaribooksonline.com/library/view/learning-python-5th/9781449355722/ch17s04.html – Pynchia Jun 04 '15 at 20:04
  • see this question/answer: http://stackoverflow.com/questions/12582720/how-to-check-in-python-that-a-file-in-a-folder-has-changed – Pynchia Jun 04 '15 at 20:08
  • if you are on Windows, there are several options available – Pynchia Jun 04 '15 at 20:09
  • as mentioned in the SO Q/A I posted above, it looks like the py-notify lib is kinda crappy (maybe it's been refactored and it's great now) http://www.serpentine.com/blog/2008/01/04/why-you-should-not-use-pyinotify/ – Pynchia Jun 04 '15 at 20:12
  • This seems a lot more complex than I thought it would be. What if I use threading.Thread() to start my polling function, then declare my trigger with `nonlocal` or `global` from within the polling function. – user1566200 Jun 04 '15 at 20:14
  • oh, yes, why not. Although I'd try not re-invent the wheel (unless it's for fun) and use a stable lib. This one looks promising: https://pypi.python.org/pypi/watchdog – Pynchia Jun 04 '15 at 20:16

0 Answers0