首页 > 解决方案 > 如何协调在 2 个不同脚本之间传递数据?

问题描述

我有 python (3.6) 脚本 A.py,它调用脚本 B.py (python 2)。

我想将一个列表(1000+ 个浮点值)作为参数传递给脚本 B,但这不起作用,所以我使用了 pickle。它工作正常。

脚本 B 进行计算并返回结果。

如何将结果传递回脚本 A ?以及如何让仍在运行的脚本 A 等待结果?

标签: python

解决方案


这是一种可能性:

A.py 可以通过Popen在模块中使用将参数subprocess设置为来调用 B.py :stdoutsubprocess.PIPE

import subprocess

command = ['B.py', 'argument-1', 'argument-2', ..., 'argument-n']
p = subprocess.Popen(command, stdout=subprocess.PIPE)
output = p.communicate() # (stdout, stderr) as bytes
results = output[0].decode() # stdout as a string

Script By 只会将其输出打印到stdout. json如果结果是结构化的,这可能是一个字符串。例如,By 的输入也可以json是 By 将从中读取的字符串stdin

import subprocess

command = ['B.py']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
json = '{"x": 1, "y": 2}'
json_as_bytes = json.encode()
output = p.communicate(input=json_as_bytes) # (stdout, stderr) as bytes
results = output[0].decode() # stdout as a string

推荐阅读