首页 > 解决方案 > 内联 Python 支持从 perl 传递文件句柄

问题描述

在尝试将 Inline python 作为从 perl 到 python 的接口时,我面临以下问题。这是代码,其中 fun 是 python 中的一个子例程,我试图从 perl 调用它

测试.pl:

use Inline Python => <<END;

def fun(fh):
    print(fh)
END

my $FH;
open($FH, ">", '/tmp/x.cth');
print $FH "hello\n";
fun($FH);

当我执行 test.pl 时,它会打印“None”,并且它无法将 FileHandle 传递给 python 代码。或将 None 传递给 python。任何建议如何解决这个问题?

标签: pythonperl

解决方案


您不能将 Perl 文件句柄传递给 Python。但是您可以尝试传递文件描述符

use feature qw(say);
use strict;
use warnings;
use Inline Python => <<END;
import os
def fun(fd):
    with os.fdopen(int(fd), 'a') as file:
        file.write("Hello from Python")
END

my $fn = 't.txt';
open (my $fh, ">", $fn) or die "Could not open file '$fn': $!";
say $fh "hello";
$fh->flush();
fun(fileno($fh));
close $fh

t.txt脚本运行后的内容为:

$ cat t.txt
hello
Hello from Python

推荐阅读