所以我正在为我公司的工作流程开发一个自动化脚本.我用Python编写了全部内容,因为我们的大多数数据库API都是用Python编写的.但是,我们的一个数据库使用Perl作为其API.显然,如果不是几个月,将他们优秀的API移植到python中需要数周时间.所以,我认为这可能是一个简单的问题,如何从我的Python脚本的主函数中获取数组,将其作为输入提供给我的Perl脚本,然后将修改后的版本返回到我的主Python脚本中?
非常感谢您的帮助!
我使用三个脚本创建了一个示例.
第一个是创建列表的Python脚本,然后将其写入JSON文件.然后我们有一个读取JSON的Perl脚本,修改它(向数组添加三个元素),然后将其写回JSON数据文件.Python中的最后一个脚本显示了如何读取JSON并使用数据.
Python脚本,创建一个列表,将其写入json文件
import json
data = [1, 2, 3]
with open('data.json', 'w') as jsonfile:
json.dump(data, jsonfile)
Run Code Online (Sandbox Code Playgroud)
数据文件现在看起来像:
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
Perl脚本,读取JSON文件,粘贴数据,将其写回:
use warnings;
use strict;
use JSON;
my $file = 'data.json';
# read in json from Python
my $json;
{
local $/;
open my $fh, '<', $file or die $!;
$json = <$fh>;
close $fh;
}
my $array = decode_json $json;
# modify the list (array)
push @$array, (4, 5, 6);
# re-encode the changed data, write it back to a json file
$json = encode_json $array;
open my $fh, '>', $file or die $!;
print $fh $json;
close $fh or die $!;
Run Code Online (Sandbox Code Playgroud)
数据文件现在看起来像:
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
Python脚本,读取更新的JSON文件,并将其转换回列表:
import json
file = 'data.json';
data = json.loads(open(file).read())
print(data)
Run Code Online (Sandbox Code Playgroud)
打印:
[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |