penitent_tangent
penitent_tangent

Reputation: 772

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!

Upvotes: 6

Views: 13905

Answers (2)

koffein
koffein

Reputation: 1882

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.

Upvotes: 2

James
James

Reputation: 1238

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.

Upvotes: 7

Related Questions