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
使用
popen
运行Perl解释器并执行所需的代码。运行Perl时,包括-m MODULE
开关以加载所需的模块,以及-e EXPRESSION
以执行所需的函数。例如,此代码在POSIX
模块中运行一个函数并获得其(字符串)结果:如果需要在Python和Perl之间传输更复杂的数据结构,请使用两种语言都支持的中间格式,例如JSON:
今天做了一些类似的事情,在http://www.boriel.com/files/perlfunc.py使用了一个名为
perlfunc.py
的模块。测试时间:
对perlfunc.py进行了微调:
raise RuntimeError(a.communicate()[1])
(第41行)very_old.pl
:reuse_very_old_perl_sub.py
:来自Presenting PyPerler(github):
如果您安装了Class::Inspector CPAN包,那么PyPerler甚至可以让您在IPython中使用内省。
相关问题 更多 >
编程相关推荐