简体   繁体   中英

How to use Perl objects and Methods in Python

I need to use previously developed Perl code in my new python script I am writing. The issue I am running into is that I cannot import the Perl files into the python code using import because they are all written in Perl. Is there a way I can bypass this and still use the perl code somehow with my python code to not have to rewrite 50+ perl programs.

An Example

in a perl file, I could have something that defines an object car that has the color red, make nissan, and model altima, and I need to be able to implement that into my python code.

You cannot reasonably combine Perl and Python code directly. While there are some ways to achieve interoperability (such as writing glue code in C), it will be far from seamless and probably take more effort than rewriting all the code.

What I try to do in that situation is to wrap the old code with a simple command-line interface. Then, the Python code can run the Perl scripts via subprocess.run() or check_output() . If complex data needs to be transferred between the programs, it's often simplest to use JSON. Alternatively, wrapping the old code with a simple REST API might also work, especially if the Perl code has to carry some state across multiple interactions.

This works fine for reusing self-contained pieces of business logic, but not for reusing class definitions.

If you could modify (instead of rewriting) the Perl code, you could have it dump JSON data so that the Python scripts could read it in. Here's an example.

Original Perl script:

use warnings;
use strict;

use JSON;

my $file = 'data.json';

my %h = (
   foo => 'bar',
   baz => ['a', 'b', 'c'],
   raz => {
       ABC => 123,
       XYZ => [4, 5, 6],
   }
);

my $json = encode_json \%h;

open my $fh, '>', $file or die $!;

print $fh $json;

close $fh or die $!;

Python script reading the data:

#!/usr/bin/python

import json

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

print(data)

Essentially, it's data output translation. Dump the data in an agreed format, and read it back in. This way, you need not have to worry about running one program from a language from the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM