0

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")
2
  • can you print the output? Commented Jul 5, 2019 at 10:15
  • 2
    You can insert something like print("MARKER") right before print(out_dict) and then split val on this marker string and use only the second field of the split. Given that both scripts are in Python, wouldn't it be easier/better to just import one into the other and then directly pass dictionaries? Commented Jul 5, 2019 at 10:21

4 Answers 4

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

0

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)

Comments

0

Two ways of doing this:

  1. Store the output dictionary in another file which is then read by script2.py
  2. As Daniel suggested, use a marker. It would remove the burden of another file but you would need an appropriate marker.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.