简体   繁体   中英

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

I'm resurrecting some orphaned code, which is written in Perl but uses inline Python. A call to the Python module returns an array of dicts or Python objects. I'm really struggling with how to access the data structures within - if I try to straight out log (print) the data structure, it appears to give the data fine, but if I index the top level array (or iterate in a list) it tells me the it's not an array reference. If I try use Dumper on the object I get:

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

Any ideas how I can use (or convert) this object?

EDIT: sample code is below. This requires a Google Music account, installing the gmusicapi python module (for they python side; obviously inline python for the perl side). Interestingly, I wrote some python code and dumped into the Inline Python section only the data structure that the API call returned - it worked fine (see https://gist.github.com/askvictor/119c24b6fc46a77b349b307457e1a027 ). When I actually put the API call into the Inline Python section, it breaks at line 4 with 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

I've got this working through a 'useless' list comprehension inside a py_eval() . It seems that Perl's Inline Python doesn't handle lists of the type future.types.newlist.newlist that are returned from the python code. So this code converts those into plain old lists, which Perl can then handle.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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