I have a few functions written in a Perl module. I have to call these functions in Python and get the output.
I have seen the link http://en.wikibooks.org/wiki/Python_Programming/Extending_with_Perl. I am not able to find the Perl module which they have imported in Python.
When I try to install pyperl in Linux, it is not able to find it.
I am able to run simple Perl script and get the output, but I am unable to call a function written in Perl and get the output.
It is possible to call Perl functions and modules in Python. One way to do that is the PyPerl Module.
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.
Use popen
to run the Perl interpreter and execute the desired code. When running Perl, include the -m MODULE
switch to load the desired module(s) and -e EXPRESSION
to execute the function you want. For example, this code runs a function in the POSIX
module and obtains its (string) result:
>>> os.popen('''
... perl -mPOSIX -e "print POSIX::asctime(localtime)"
... ''').read()
'Sun Jan 19 12:14:50 2014\n'
If you need to transmit more involved data structures between Python and Perl, use an intermediate format well supported in both languages, such as JSON:
>>> import os, json
>>> json.load(os.popen('''
... perl -e '
... use POSIX qw(localtime asctime);
... use JSON qw(to_json);
... my @localtime = localtime(time);
... print to_json({localtime => \@localtime,
... asctime => asctime(@localtime)});
... '
... '''))
{u'localtime': [10, 32, 12, 19, 0, 114, 0, 18, 0],
u'asctime': u'Sun Jan 19 12:32:10 2014\n'}
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