10

这是我的问题的最简单的可重现性:

#!/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代码无法打印到重定向的输出?

4

2 回答 2

8

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
于 2021-08-05T04:58:30.923 回答
2

完整的事情是:

BEGIN {
    # Unbuffer Python's output
    $ENV{PYTHONUNBUFFERED}=1;

    # Unbuffer Perl's output
    select((select(STDOUT), $|=1)[0]);
    select((select(STDERR), $|=1)[0]);
}
...
END { 
    # Shut down the Python interpreter.
    Inline::Python::py_finalize();
}

必须取消缓冲 Perl 的输出。感谢 ikegami 在一篇现已删除的帖子中对此发表了评论,并提醒了我关于py_finalize().

于 2021-08-05T20:07:41.590 回答