繁体   English   中英

如何在 Perl 中使用(或转换或查看)内联 Python 对象?

[英]How do I use (or convert, or view) inline Python objects in Perl?

我正在复活一些用 Perl 编写但使用内联 Python 的孤立代码。 对 Python 模块的调用将返回一个 dicts 或 Python 对象数组。 我真的很纠结如何访问其中的数据结构 - 如果我尝试直接记录(打印)数据结构,它似乎可以很好地提供数据,但是如果我索引顶级数组(或在列表中迭代) ) 它告诉我它不是数组引用。 如果我尝试在对象上使用 Dumper,我会得到:

$VAR1 = bless( do{\(my $o = '140162464462376')}, 'Inline::Python::Object' );

我有什么想法可以使用(或转换)这个对象吗?

编辑:示例代码如下。 这需要一个 Google Music 帐户,安装 gmusicapi python 模块(对于他们的 python 端;显然是 perl 端的内联 python)。 有趣的是,我编写了一些 python 代码,并将 API 调用返回的数据结构转储到 Inline Python 部分 - 它工作正常(参见https://gist.github.com/askvictor/119c24b6fc46a77b349b307457e1a027 )。 当我实际将 API 调用放入内联 Python 部分时,它在第 4 行中断, Not an ARRAY reference at sample.pl line 4.

use strict;
use warnings;

my $data = search("radiohead");
print "$data\n";
print "$data->{song_hits}\n";
print "$data->{song_hits}[0]\n";
for my $hit (@{$data->{song_hits}}){
    print "$hit->{track}->{title}\n";
}

use Inline Python => <<'END_OF_PYTHON_CODE';
import gmusicapi

USERNAME="my_username@gmail.com"
PASSWORD="sooper_secr3t"
DEVICE_ID = "12345abcde123" # this can be obtained using https://raw.githubusercontent.com/squeezebox-googlemusic/squeezebox-googlemusic/master/mobile_devices.py
def search(needle):
    c = gmusicapi.Mobileclient()
    c.login(USERNAME, PASSWORD, DEVICE_ID)
    r = c.search(needle, 2)
    return r
END_OF_PYTHON_CODE

我已经通过py_eval()的“无用”列表理解来解决这个py_eval() Perl 的内联 Python 似乎不处理从 python 代码返回的future.types.newlist.newlist类型的列表。 所以这段代码将它们转换成普通的旧列表,然后 Perl 可以处理这些列表。

my $song_hits = py_eval("[x for x in $data->{song_hits}]", 0);
for my $hit (@$song_hits) {
    print $hit->{track}->{title};
    print "\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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