![](/img/trans.png)
[英]Inline Python how to convert filter objects from Python to arrays or iterator at least in Perl
[英]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.