【问题标题】:Inline - Accessing python variables from python in perl内联 - 在 perl 中从 python 访问 python 变量
【发布时间】:2021-04-23 17:41:21
【问题描述】:

use Inline Python => <<END;
var_py = "test"

END
my $var1 = "from_perl";
print "var1 $var1\n";
print "variably from py $var_py\n";

输出:

var1 from_perl

从 py 可变

我得到了内联 Python 中定义的 Python 变量的空值。 有人可以建议如何从 perl 读取 python 中定义的变量

【问题讨论】:

  • 提示:使用&lt;&lt;'END' 而不是&lt;&lt;END 意味着您不必逃避任何事情

标签: python perl


【解决方案1】:
use Inline Python => ( <<'__EOS__' =~ s/^[ ]{3}//mgr );

   import sys

   var_py = "test"

   def get_var_py():
      return var_py

   def _get_global_var(name):
      name = name.decode('UTF-8')
      return globals()[name]

   def _get_module_var(mod_name, var_name):
      mod_name = mod_name.decode('UTF-8')
      var_name = var_name.decode('UTF-8')
      return getattr(sys.modules[mod_name], var_name)

__EOS__

sub get_global_var { my @args = @_; utf8::encode($_) for @args; _get_global_var(@args) }
sub get_module_var { my @args = @_; utf8::encode($_) for @args; _get_module_var(@args) }

say "Variable from py: " . get_var_py();
say "Variable from py: " . get_global_var('var_py');
say "Variable from py: " . get_module_var('__main__', 'var_py');

输出

Variable from py: test
Variable from py: test
Variable from py: test

【讨论】:

  • 嗨,我只是举了一个变量的例子,我有多个这样的变量在 python 模块中定义为常量,并希望从 perl 访问它们。有什么办法吗?
  • 添加到答案。 Ref
猜你喜欢
  • 2020-10-26
  • 2012-07-25
  • 1970-01-01
  • 2018-05-05
  • 2022-08-11
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多