Andras Palfi Andras Palfi - 1 year ago 56
Python Question

Feeding a Python array into a Perl script

So I'm working on an automation script for a workflow in my company. I have written the whole thing in Python, as most of our databases API's were in Python. However, one of our databases uses Perl for their API. It would obviously take me weeks if not months to port their excellent API into python. So, and I assume this is probably a simple problem, how can I take an array from the main function of my Python script, feed it into my Perl script as input, then return the modified version back into my main Python script?

Thank you very much for any help!

Answer Source

I've created an example using three scripts.

The first one is a Python script that creates a list, then writes it to a JSON file. We then have a Perl script that reads in the JSON, modifies it (adds three more elements to the array), then writes it back to the JSON data file. The last script, in Python, shows how to read in JSON and use the data.

Python script, create a list, write it out to a json file

import json

data = [1, 2, 3]

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

The data file now looks like:

[1, 2, 3]

Perl script, reads the JSON file, mucks with the data, writes it back out:

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

Data file now looks like:

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

Python script, reads the updated JSON file, and transforms it back into a list:

import json

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



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