[英]How to call a Perl function in Python
我有一些用 Perl 模塊編寫的函數。 我必須在 Python 中調用這些函數並獲取輸出。
我已經看到鏈接http://en.wikibooks.org/wiki/Python_Programming/Extending_with_Perl 。 我找不到他們在 Python 中導入的 Perl 模塊。
當我嘗試在 Linux 中安裝 pyperl 時,它無法找到它。
我能夠運行簡單的 Perl 腳本並獲得輸出,但我無法調用用 Perl 編寫的函數並獲得輸出。
使用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
的模塊。
測試:
對 perlfunc.py 進行了微調:
raise RuntimeError(a.communicate()[1])
(第 41 行) 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!')
來自展示 PyPerler ( github ):
我花了一些空閑時間編寫了一個 Python -> Perl 接口。 現有的解決方案pyperl最初是為非常舊的 Python 版本編寫的,不再編譯。 同時,由於 Cython,為 Python 編寫 C 擴展變得更加容易。 我認為從頭開始並編寫 PyPerler 是有意義的。 幸運的是,我使用了 PyPerl 的 Perl 代碼來包裝 Python 對象。 在 Python 方面,一切都是新的。
PyPerler 在 Python 中為您提供 CPAN 和您的(遺留?)perl 包的強大功能。 使用 Perl 的東西很簡單:
>>> 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 中的使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.