5

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!

3
  • Take a look at data serialization (also known as "pickling"): In perl and in python Commented Jun 2, 2016 at 13:48
  • 5
    JSON is quite a good bet for being able to represent the data types in different languages. Commented Jun 2, 2016 at 14:07
  • 2
    @machineyearning "Pickling" is a python-specific term. Commented Jun 2, 2016 at 20:34

1 Answer 1

6

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())

print(data)

Prints:

[1, 2, 3, 4, 5, 6]
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thank you! This was exactly the sort of thing I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.