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!
Type "pyth. RunPerl. ext;" where "Full Path To File" is the full path filename of your Perl file. This will cause Python to execute the Perl file, then continue down the line with the rest of your Python code.
The @ARGV array holds the command line argument. There is no need to use variables even if you use "use strict". By default, this variable always exists and values from the command line are automatically placed inside this variable. To access your script's command-line arguments, you just need to read from @ARGV array.
Here are the simple steps to convert PERL scripts to Python. Remove all ';' at the end of the line. Remove all curly brackets and adjust indentation. Convert variables names from $x, %x or @x to x.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With