python - 内联 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。任何建议如何解决这个问题?
解决方案
您不能将 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
推荐阅读
- netsuite - 如何从 SuiteScript 2.0 Suitelet 中检索值以进行 POST?
- c# - LINQ2SQL 表达式 - 转换日期时转换失败
- c# - DependencyObject 不能很好地处理对象属性的相等性
- fortran - Fortran 不对数组或程序变量调用 FINAL
- php - 如何将按钮文本从阅读更多更改为帖子类别和 wordpress 中的其他文本?
- java - Java 11 升级缺少 javax.annotation.security
- excel - VBA Excel 宏 - 显示与列相关的单元格值
- javascript - 具有页面对象模型的量角器(打字稿错误)
- sql - 如何使用按网格中的单元格分组的 SQL 进行计数?
- python - 了解生成器内部的 StopIteration 处理非平凡情况