1

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

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

Output:

var1 from_perl

variably from py

I get empty value for the python variable defined in Inline Python. Can someone please suggest how to read variables defined in python from perl

1
  • Tip: Using <<'END' instead of <<END means you don't have to escape anything Commented Jan 19, 2021 at 12:40

1 Answer 1

3
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');

Output

Variable from py: test
Variable from py: test
Variable from py: test
Sign up to request clarification or add additional context in comments.

2 Comments

Hi , I just gave an example of one variable, I have multiple such variables defined as constants in a python module and wants to access them from perl. Is there any way?
Added to answer. Ref

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.