【问题标题】:Feeding a Python array into a Perl script将 Python 数组输入 Perl 脚本
【发布时间】:2016-10-02 06:57:52
【问题描述】:

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

非常感谢您的帮助!

【问题讨论】:

  • 看看数据序列化(也称为“酸洗”):In perlin python
  • JSON 是一个很好的选择,因为它能够用不同的语言表示数据类型。
  • @machineyearning “Pickling”是 Python 特有的术语。

标签: python perl


【解决方案1】:

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

第一个是创建列表,然后将其写入 JSON 文件的 Python 脚本。然后我们有一个 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]

【讨论】:

  • 哇,谢谢!这正是我正在寻找的东西!
猜你喜欢
  • 2015-08-20
  • 2017-11-21
  • 1970-01-01
  • 2012-01-02
  • 2015-11-13
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多