如何在Python中调用Perl函数

2024-04-20 02:55:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个用Perl模块编写的函数。我必须用Python调用这些函数并获得输出。

我看到了联系 http://en.wikibooks.org/wiki/Python_Programming/Extending_with_Perl。我找不到他们在Python中导入的Perl模块。

当我试图在Linux中安装pyperl时,它找不到它。

我能够运行简单的Perl脚本并获得输出,但是我无法调用用Perl编写的函数并获得输出。


Tags: 模块函数org脚本httplinuxwithwiki
3条回答

使用popen运行Perl解释器并执行所需的代码。运行Perl时,包括-m MODULE开关以加载所需的模块,以及-e EXPRESSION以执行所需的函数。例如,此代码在POSIX模块中运行一个函数并获得其(字符串)结果:

>>> os.popen('''
... perl -mPOSIX -e "print POSIX::asctime(localtime)"
... ''').read()
'Sun Jan 19 12:14:50 2014\n'

如果需要在Python和Perl之间传输更复杂的数据结构,请使用两种语言都支持的中间格式,例如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'}

今天做了一些类似的事情,在http://www.boriel.com/files/perlfunc.py使用了一个名为perlfunc.py的模块。

测试时间:

  • Python2.7.12
  • perl 5,版本22,subversion 1(v5.22.1),为x86_64-linux-gnu-thread-multi构建

对perlfunc.py进行了微调:

  • raise RuntimeError(a.communicate()[1])(第41行)
  • 从第132行删除“已定义”

very_old.pl

#!/usr/bin/perl
sub hello($)
{
   my $d = shift;
   return "Hello, $d!";
}

1;

reuse_very_old_perl_sub.py

#!/usr/bin/python
from perlfunc import perlfunc, perlreq, perl5lib

@perlfunc
@perlreq('very_old.pl')
def hello(somebody):
    pass


if __name__ == '__main__':
    assert(hello('python-visit-perl') == 'Hello, python-visit-perl!')

来自Presenting PyPerlergithub):

I spent some spare time writing a Python -> Perl interface. The existing solution pyperl was originally written for very old versions of Python and doesn't compile anymore. In the mean time, writing C extensions to Python has become much easier thanks to Cython. I thought it made sense to start from scratch and wrote PyPerler. I thankfully made use of the PyPerl's Perl code for wrapping a Python object. On the Python side, everything is new.

PyPerler gives you the power of CPAN, and your (legacy?) perl packages, in Python. Using Perl stuff is as easy as:

>>> import pyperler; i = pyperler.Interpreter()
>>> # use a CPAN module
>>> Table = i.use('Text::Table')
>>> t = Table("Planet", "Radius\nkm", "Density\ng/cm^3")
>>> _ = t.load(
...    [ "Mercury", 2360, 3.7 ],
...    [ "Venus", 6110, 5.1 ],
...    [ "Earth", 6378, 5.52 ],
...    [ "Jupiter", 71030, 1.3 ],
... )
>>> for line in t.table(): print line
Planet  Radius Density
        km     g/cm^3 
Mercury  2360  3.7    
Venus    6110  5.1    
Earth    6378  5.52   
Jupiter 71030  1.3

如果您安装了Class::Inspector CPAN包,那么PyPerler甚至可以让您在IPython中使用内省。

相关问题 更多 >