内联 Python 支持从 perl 传递文件句柄
Inline Python support for passing filehandle from perl
在尝试将内联 python 作为从 perl 到 python 的接口时,我遇到了以下问题。
这是代码,其中 fun 是 python 中的一个子例程,我试图从 perl
中调用它
test.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。有什么解决方法的建议吗?
您不能将 Perl 文件句柄传递给 Python。但是你可以尝试传递一个 file descriptor:
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
在尝试将内联 python 作为从 perl 到 python 的接口时,我遇到了以下问题。 这是代码,其中 fun 是 python 中的一个子例程,我试图从 perl
中调用它test.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。有什么解决方法的建议吗?
您不能将 Perl 文件句柄传递给 Python。但是你可以尝试传递一个 file descriptor:
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