Reputation: 479
I have a python script 'script1.py' which creates a dictionary 'out_dict' at the end of the execution. I'm calling 'script1.py' from another script 'script2.py'.
Is there any way to get only the final dictionary 'out_dict' (note : I have some print statements too in 'scirpt1.py') into a variable in 'script2.py'.
script1.py
......
......
some print statement
......
some print statement
......
out_dict = {...}
print(out_dict)
script2.py
import os
val = os.system("python3.6 script1.py")
Upvotes: 0
Views: 6151
Reputation: 512
At the start of script1.py
add
import pickle as p
and after your dict was created add
with open('dict.p', 'wb') ad f:
p.dump(out_dict, f)
Then in script2.py
again import pickle but this time load from a file
import os
import pickle as p
val = os.system("python3.6 script1.py")
with open('dict.p', 'rb') as f:
your_dict = p.load(f) # your dict will loaded
OR
You can not save your dict into a file at all and just access it from script1.py
like a class var, but you will have to import your first script though.
script2.py
example:
import script1
your_dict = script1.out_dict # your dict var from the first script
print (out_dict)
Upvotes: 2
Reputation: 163
Easier method would be to import one file in another and use that dictionary:
func.py
def function():
out_file=dict()
# Your Code
return out_file
main.py
import func
val = func.function()
Upvotes: 1
Reputation: 2543
Two ways of doing this:
Upvotes: 0
Reputation: 922
You need to declare 2 files. The first will contain the function you want to call. Like this:
func.py
def myFunc():
return 2
In the script you want to call the function you have to do this:
main_script.py
import func
val = func.myFunc()
print(val)
Upvotes: 0