简体   繁体   中英

Inline Python support for passing filehandle from perl

While Trying Inline python as a interface from perl to python, I am facing below issue. This is the code where fun is a subroutine inside python and I am trying to call it from 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);

When I execute test.pl, It prints "None", and its not able to pass FileHandle to python code. Or passing None to python. Any suggestions how to fix this?

You cannot pass a Perl filehandle to Python. But you can try pass a 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

The content of t.txt after running the script is:

$ cat t.txt
hello
Hello from Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM