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?
Asked
Active
Viewed 69 times
0

prakash
- 1
- 2
-
And the question is? ... – MegaIng Jun 02 '18 at 06:45
-
is there a way in python to do this? – prakash Jun 02 '18 at 06:46
-
1Possible duplicate of [What is the best way to call a Python script from another Python script?](https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script) – cdarke Jun 02 '18 at 06:55
-
This is different @cdarke – prakash Jun 06 '18 at 14:06
1 Answers
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
-
-
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