【问题标题】:Inline Python support for passing filehandle from perl内联 Python 支持从 perl 传递文件句柄
【发布时间】:2021-04-12 10:18:14
【问题描述】:

在尝试将 Inline 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。有什么建议可以解决这个问题吗?

【问题讨论】:

    标签: python perl


    【解决方案1】:

    您不能将 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
    

    【讨论】:

      猜你喜欢
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多