Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import module within loop

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!

like image 249
penitent_tangent Avatar asked Jul 02 '15 01:07

penitent_tangent


1 Answers

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.

like image 60
James Avatar answered Oct 18 '22 13:10

James