将 Perl 哈希写入磁盘以供 Python 读取
Writing a Perl hash to disk to be read by Python
如何将 Perl 散列写入文件,以便可以从 Python 中读取?
例如:
#!/usr/bin/perl
my %h = (
foo => 'bar',
baz => ['a', 'b', 'c'],
raz => {
ABC => 123,
XYZ => [4, 5, 6],
}
);
dumpHash('/tmp/myhash', %h);
... 和
#!/usr/bin/python
h = readHash('/tmp/myhash')
print h
# {
# 'foo': 'bar',
# 'baz': ['a', 'b', 'c'],
# 'raz': {
# 'ABC': 123,
# 'XYZ': [4, 5, 6]
# }
# }
我通常使用 Perl 的内置 Storable
来序列化哈希值。我看到 Python 有一个 Storable reader,但它不是标准发行版的一部分。
有没有一种方法可以使用两种语言的标准内置函数来做到这一点。
我在第一次阅读您的问题时错过了 'builtin' 要求,但我离题了。 JSON
不是 Perl 内建的,因此您必须通过 CPAN
安装。尽管如此,这可能是最有效和最兼容的方法之一。
Perl:
use warnings;
use strict;
use JSON;
my $file = 'data.json';
my %h = (
foo => 'bar',
baz => ['a', 'b', 'c'],
raz => {
ABC => 123,
XYZ => [4, 5, 6],
}
);
my $json = encode_json \%h;
open my $fh, '>', $file or die $!;
print $fh $json;
close $fh or die $!;
Python:
import json
file = 'data.json';
data = json.loads(open(file).read())
print(data)
如何将 Perl 散列写入文件,以便可以从 Python 中读取?
例如:
#!/usr/bin/perl
my %h = (
foo => 'bar',
baz => ['a', 'b', 'c'],
raz => {
ABC => 123,
XYZ => [4, 5, 6],
}
);
dumpHash('/tmp/myhash', %h);
... 和
#!/usr/bin/python
h = readHash('/tmp/myhash')
print h
# {
# 'foo': 'bar',
# 'baz': ['a', 'b', 'c'],
# 'raz': {
# 'ABC': 123,
# 'XYZ': [4, 5, 6]
# }
# }
我通常使用 Perl 的内置 Storable
来序列化哈希值。我看到 Python 有一个 Storable reader,但它不是标准发行版的一部分。
有没有一种方法可以使用两种语言的标准内置函数来做到这一点。
我在第一次阅读您的问题时错过了 'builtin' 要求,但我离题了。 JSON
不是 Perl 内建的,因此您必须通过 CPAN
安装。尽管如此,这可能是最有效和最兼容的方法之一。
Perl:
use warnings;
use strict;
use JSON;
my $file = 'data.json';
my %h = (
foo => 'bar',
baz => ['a', 'b', 'c'],
raz => {
ABC => 123,
XYZ => [4, 5, 6],
}
);
my $json = encode_json \%h;
open my $fh, '>', $file or die $!;
print $fh $json;
close $fh or die $!;
Python:
import json
file = 'data.json';
data = json.loads(open(file).read())
print(data)