python - 将 Python 数组输入 Perl 脚本

标签 python perl

所以我正在为公司的工作流程编写自动化脚本。我用 Python 编写了整个东西,因为我们的大多数数据库 API 都是用 Python 编写的。但是,我们的一个数据库使用 Perl 作为其 API。显然,将他们优秀的 API 移植到 python 中,我需要数周甚至数月的时间。所以,我认为这可能是一个简单的问题,我如何从我的 Python 脚本的主要函数中获取一个数组,将其作为输入输入到我的 Perl 脚本中,然后将修改后的版本返回到我的主要 Python 脚本中?

非常感谢您的帮助!

最佳答案

我使用三个脚本创建了一个示例。

第一个是创建列表的 Python 脚本,然后将其写入 JSON 文件。然后我们有一个 Perl 脚本读取 JSON,修改它(向数组添加三个以上的元素),然后将它写回 JSON 数据文件。最后一个 Python 脚本展示了如何读取 JSON 和使用数据。

Python脚本,创建一个列表,将其写出到一个json文件

import json

data = [1, 2, 3]

with open('data.json', 'w') as jsonfile:
    json.dump(data, jsonfile)

数据文件现在看起来像:

[1, 2, 3]

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 $!;

数据文件现在看起来像:

[1, 2, 3, 4, 5, 6]

Python 脚本,读取更新后的 JSON 文件,并将其转换回列表:

import json

file = 'data.json';
data = json.loads(open(file).read())

print(data)

打印:

[1, 2, 3, 4, 5, 6]

关于python - 将 Python 数组输入 Perl 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593542/

相关文章:

python - 如何允许打开文件名中包含 Unicode 字符的文件?

bash - 如何在 sed 和 awk(和 perl)中搜索和替换任意文字字符串

perl - 如何使用 Perl 的 WWW::Mechanize 访问没有名称或 ID 的表单?

python - 使用多个拟合图像制作图像立方体

python - 如何使用很多参数执行 python subprocess.Popen?

python - celery 获取任务计数

python - 为什么/如何迭代列表并每次调用 'pass' 修复此功能?

xml - 库 :XML for perl parsing huge xml files through xpath causing core segmentation fault

python延迟执行

perl - LWP::Simple get 的结果被截断