8

我正在学习 perl Inline::Python 库。在 cpan 网站的例子中,我们有

   print "9 + 16 = ", add(9, 16), "\n";
   print "9 - 16 = ", subtract(9, 16), "\n";

   use Inline Python => <<'END_OF_PYTHON_CODE';
   def add(x,y): 
      return x + y

   def subtract(x,y):
      return x - y

   END_OF_PYTHON_CODE

是否可以将 python 代码放入字符串中,以便我可以在运行时创建 python 代码?例如,类似:

my $python_code = "
def add(x,y):
   return x + y
";
print $python_code;
use Inline Python => "$python_code";
print "9 + 16 = ", add(9, 16), "\n";

我们有一个项目将在运行时动态创建 python 函数。我们想调用这些函数。py_eval() 是要走的路吗?提前致谢。

4

1 回答 1

5

没有经验Inline::Python,但是Inline::C 您可以使用该bind函数在运行时设置代码,所以也许这会起作用:

my $python_code = "
def add(x,y):
   return x + y
";
print $python_code;
Inline->bind( Python => $python_code );
print "9 + 16 = ", add(9, 16), "\n";
于 2012-08-06T18:25:35.973 回答