0

I have have python file a.py which has a function fun(). fun() uses some libraries and global variables from a.py. The execution of a.py takes a lot of time but the execution of fun() is very fast once the libraries and global variables are ready. So I want to run a.py only once and use this variables and libraries every time I call the function fun() from another file. For example I want to call fun() for every 2 seconds from another file. But I can't do this because a.fun() is taking more time to execute. I want to setup 'a.py' in such way that after importing libraries and executing __main__ it sleeps or stops. After that whenever I am calling a.fun() from outside it should use the libraries already imported and the global variables calculated by __main__. How to do this in python?

prakash
  • 1
  • 2

1 Answers1

1

You can use the threading module to run the function all 2 seconds regarless of how long the function takes

import a
import threading

while True:
    threading.Thread(target=a.fun).start()
    time.sleep(2)

Keep in mind that this program will only terminate if all Threads are dead.

MegaIng
  • 7,361
  • 1
  • 22
  • 35
  • That isn't the problem. If I do this all the libraries inside `a.py` will be imported again. This takes time. So the importing those libraries should take place only once. I want to call 'fun()' for every 3 seconds from another file. – prakash Jun 02 '18 at 07:25
  • @prakash Now better? – MegaIng Jun 02 '18 at 07:26
  • No. :( I want to edit a.py so that after one execution of `a.py`,`a.fun()` can be called everytime and whenever it calls `fun()` uses the libraries imported and global variables calculated during the first execution. – prakash Jun 02 '18 at 07:28