为什么无法重定向打印的Inline::Python函数?
这是我的问题最简单的重现:
#!/usr/bin/env perl
use 5.16.3;
say "Got back ", test_print();
use Inline Python => <<'END_OF_PYTHON_CODE';
def test_print() -> int:
print("In the python test print")
return 32
END_OF_PYTHON_CODE
简单运行时:
$ perl small.pl
In the python test print
Got back 32
但是当重定向时:
$ perl small.pl | tee foo
Got back 32
$ cat foo
Got back 32
我可能做错了什么,导致Inline::Python代码无法打印到重定向的输出?
回答
Py_Finalize() 未调用以正确破坏 Python 解释器。
值得庆幸的是,该模块将此函数公开为py_finalize,允许我们自己调用它。将以下内容添加到您的程序中:
END { Inline::Python::py_finalize(); }
演示:
use feature qw( say );
use Inline Python => <<'END_OF_PYTHON_CODE';
def test_print() -> int:
print("In the python test print")
return 32
END_OF_PYTHON_CODE
END { Inline::Python::py_finalize() if $ARGV[0]; }
say "Got back ", test_print();
$ perl a.pl 0
In the python test print
Got back 32
$ perl a.pl 0 | cat
Got back 32
$ perl a.pl 1
In the python test print
Got back 32
$ perl a.pl 1 | cat
In the python test print
Got back 32