ytu
ytu

Reputation: 1850

Transfer a JSON string between programs without saving a file

Let's assume I have two Python modules, first.py and second.py. first.py generates a JSON string; second.py takes a JSON string and does subsequent processes. To simplify them, consider the example written below:

# first.py
import json
fruit = input("Name a fruit: ")
material_str = json.dumps({"fruit": fruit})
print(material_str)

# second.py
import json
material = json.loads(material_str)
def blender(material):
    serving = material["fruit"] + " juice"
    return serving
print(blender(material))

Now my problem is: how to transfer material_str from first.py to second.py? Is there a way to make material_str somehow cached in the memory and then taken by second.py (or even more general, by programs in other languages which can load JSON strings)? Because it seems unlikely that the printed string can be transferred like this.

I know I can json.dump the dictionary into a file in first.py, and json.load it in second.py. However, these codes will be executed thousands of times a day and the JSON strings are useful only during the execution, so I don't want to save them. Combining first.py and second.py is not feasible either because in fact they are two big projects developed by different people. In fact, consider first.py as a script doing OCR and second.py as a script of one iOS app. Now the results of OCR need to be transferred to the app script so that they can be presented.

I have read some documentation about sys.stdout but it looks like no luck. Any help is appreciated.

Upvotes: 0

Views: 654

Answers (1)

ytu
ytu

Reputation: 1850

This question is totally solvable in Python. In my case, the only thing I need is testing whether the JSON string can be transferred across programs without saving a file, like I indicated in the title.

What I need is subprocess module in second.py to execute first.py in a subprocess, and then pipe the results for subsequent procedures.

import json
import subprocess
import re
# Get stdout from first.py
raw_result = subprocess.run(["python", "first.py"], stdout=subprocess.PIPE)
# Capture the JSON string
material_str = re.search(r".+({.+})", str(raw_result.stdout)).group(1)
# Load the JSON string as a dictionary
material = json.loads(material_str)
# Make juice
def blender(material):
    serving = material["fruit"] + " juice"
    return serving
print(blender(material))

By executing python second.py and entering "Apple", it returns "Apple juice" perfectly.

Upvotes: 1

Related Questions