Python 在程序之间传输JSON字符串而不保存文件

Python 在程序之间传输JSON字符串而不保存文件,python,json,transfer,Python,Json,Transfer,假设我有两个Python模块,first.py和second.pyfirst.py生成一个JSON字符串second.py接受JSON字符串并执行后续处理。为了简化它们,考虑下面的例子: # first.py import json fruit = input("Name a fruit: ") material_str = json.dumps({"fruit": fruit}) print(material_str) # second.py import json material = j

假设我有两个Python模块,
first.py
second.py
first.py
生成一个JSON字符串
second.py
接受JSON字符串并执行后续处理。为了简化它们,考虑下面的例子:

# 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))
现在我的问题是:如何将
物料从
first.py
转移到
second.py
?有没有办法让
material\u str
以某种方式缓存在内存中,然后由
second.py
获取(或者更一般地说,由其他语言的程序加载JSON字符串)?因为
print
ed字符串不太可能像这样传输

我知道我可以
json.dump
将字典放入
first.py
中的一个文件中,并
json.load
装入
second.py
中。但是,这些代码每天将执行数千次,JSON字符串仅在执行期间有用,因此我不想保存它们。将
first.py
second.py
结合起来也不可行,因为实际上它们是由不同的人开发的两个大项目。事实上,请考虑<代码>第一。Py < /C>作为OCR和<代码>脚本的第二。Py <代码>作为一个iOS应用程序的脚本。现在,OCR的结果需要传输到应用程序脚本,以便能够显示


我读过一些关于sys.stdout的文档,但是看起来运气不好。非常感谢您的帮助。

这个问题在Python中完全可以解决。在我的例子中,我唯一需要的是测试JSON字符串是否可以在不保存文件的情况下跨程序传输,就像我在标题中指出的那样

我需要的是second.py中的
subprocess
模块在子流程中执行first.py,然后将结果输送到后续过程

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

通过执行
python second.py
并输入“Apple”,它会完美地返回“Apple juice”。

我猜您是说在两个不同的进程之间共享内存资源?否则这个问题就没什么意义了(你可以共享一个全局变量,将它发送给函数或其他许多方法..)。它们应该如何“传递”?第一个脚本在哪里运行,第二个脚本在哪里运行?iOS应用程序和linux服务器上的进程如何通信???如果您不知道进程应该如何通信,那么很难回答。您需要先确定系统将如何通信,然后再确定它们将如何通信