python - 如何协调在 2 个不同脚本之间传递数据?
问题描述
我有 python (3.6) 脚本 A.py,它调用脚本 B.py (python 2)。
我想将一个列表(1000+ 个浮点值)作为参数传递给脚本 B,但这不起作用,所以我使用了 pickle。它工作正常。
脚本 B 进行计算并返回结果。
如何将结果传递回脚本 A ?以及如何让仍在运行的脚本 A 等待结果?
解决方案
这是一种可能性:
A.py 可以通过Popen
在模块中使用将参数subprocess
设置为来调用 B.py :stdout
subprocess.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
推荐阅读
- c# - .net Core 2 包含然后包含不起作用
- sql - 您将如何检索整个列
- java - 如何关闭 Grizzly 日志记录?
- c++ - 为什么我的变量在其范围之外
- python - JWT 如何与 django-phonenumber-field 一起使用
- c# - 是否有任何 Dot Net 服务来计算 Xliff 文件中的单词?
- apt - Debian Stretch 更新问题
- sql - 根据 Hive 中 2 个源表中的一些规则更新目标中的“标志”
- google-cloud-platform - 如何根据条件运行 Apache Beam 写入大查询
- java - 参数中0有什么意义--String message=new String(recievepacket.getData(),0,recievepacket.getLength());