Serving Python array in Perl script

So, I am working on a script automation for a workflow in my company. I wrote all this in Python, since most of our database APIs were in Python. However, one of our databases uses Perl for its API. Obviously, it will take me several weeks, if not months, to pass their excellent API in python. So, and I guess this is probably a simple problem, how can I take an array from the main function of my Python script, pass it to my Perl script as input, and then return the modified version back to my main Python script?

Thanks so much for any help!

+5
source share
1 answer

I created an example using three scenarios.

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

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

import json data = [1, 2, 3] with open('data.json', 'w') as jsonfile: json.dump(data, jsonfile) 

Now the data file is as follows:

 [1, 2, 3] 

Perl script, reads the JSON file, flushes the data and writes it back:

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

The data file now looks like this:

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

Python script, reads the updated JSON file and converts it back to a list:

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

Print

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

All Articles