6

I have one file, let's call it foo.py. It does a couple of things, including sending some data over a serial port and emailing the response that comes back.

I have another file, which looks something like this:

iteration = 0
while True:
    iteration += 1
    // do some stuff here every time
    if iteration%5 == 0:
        import foo
    time.sleep (100)

I'm aware there are some broader problems here with the elegance (or lack thereof) of an independent counter, but putting that aside - the serial transmission / email only works the first time it's triggered. Subsequent loops at a multiple of 5 (which will trigger the modulo 5 == 0) do nothing.

Does my imported version of foo.py get cached, and avoid triggering on subsequent runs? If yes, how else can I call that code repeatedly from within my looping script? Should I just include it inline?

Thanks for any tips!

penitent_tangent
  • 762
  • 2
  • 8
  • 18

2 Answers2

7

If you have access to foo.py, you should wrap whatever you want to run in foo.py in a function. Then, just import foo once and call the function foo.func() in the loop.

See this for an explanation of why repeated imports does not run the code in the file.

Community
  • 1
  • 1
James
  • 1,198
  • 8
  • 14
2

You can replace import foo with

if 'foo' in dir(): # if it has already been imported
    reload(foo)
else:
    import foo

Not quite sure, but this should work. Edit: Now I am sure.

koffein
  • 1,792
  • 13
  • 21
  • 2
    Yes, it should work, but ___please___ don't do this. The `reload()` function should really only be used during development, when you're working in an interactive interpreter and you need to reload a module that you've modified. See [the docs for reload()](https://docs.python.org/2/library/functions.html#reload). Note that in Python 3, `reload()` is _not_ a built-in, you have to import it from [imp](https://docs.python.org/3/library/imp.html#imp.reload) or [importlib](https://docs.python.org/3/library/importlib.html#importlib.reload). – PM 2Ring Jul 02 '15 at 01:22
  • @PM2Ring Yes, you are right, but I actually think the OP is aware of that. – koffein Jul 02 '15 at 01:25
  • Perfect, thanks. I wasn't aware this is an option and it's good to know too :) – penitent_tangent Jul 02 '15 at 01:28