Reputation: 213
Let's say in a file A.py
and I am computing value of some variable x
by some lengthy procedure, such that code takes around 15-30 seconds to execute.
I want to use value of x
in another program B.py
.
I have thought of importing x
to another file B.py
but when B
executes, it executes A
again in order to calculate x
. B
takes another 1-2 minutes to execute, so it's essential that I just use the output x
. I tried to put it under if __name__ == "main"
, but how will I compute x
then?
Also, I have tried copying the value of x
to a text file as mentioned here, but x
is a very large list (around 10000 length), so output just shows "..." and omits printing most of it.
Upvotes: 0
Views: 64
Reputation: 975
When you don't need to run A.py
for any other reason except to produce x
(to be used i B.py
), then you could simply have the code that returns x
in a function called compute_x()
and then in B.py
write from A import compute_x
and call the function in B.py
.
Upvotes: 0
Reputation: 1553
I think you want to use pickle.
import pickle
very_long_list = [1,2,3]
file_name = "/tmp/very_long_list.pickle"
pickle.dump(very_long_list, open(file_name, "wb"))
del very_long_list
very_long_list = pickle.load(open(file_name, "rb"))
print(very_long_list) # prints [1,2,3], we did it!
Upvotes: 2