gpt4 book ai didi

python - 内联 Python 支持从 perl 传递文件句柄

转载 作者:行者123 更新时间:2023-12-02 19:00:48 24 4
gpt4 key购买 nike

在尝试将内联 python 作为从 perl 到 python 的接口(interface)时,我面临以下问题。这是代码,其中 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。有什么建议如何解决这个问题吗?

最佳答案

您无法将 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 - 内联 Python 支持从 perl 传递文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65599664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com