从Python运行Lua脚本 [英] Run Lua script from Python

查看:1083
本文介绍了从Python运行Lua脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含2个函数的Lua脚本.我想用Python脚本中的一些参数调用这些函数.

Suppose I have a Lua script that contains 2 functions. I would like to call each of these functions with some arguments from a Python script.

我看过有关如何使用Lunatic Python将Lua代码嵌入Python以及反之亦然的教程,但是,我要在Python脚本中执行的Lua函数不是静态的,并且可能会发生变化.

I have seen tutorials on how to embed Lua code in Python and vice versa using Lunatic Python, however, my Lua functions to be executed in the Python script are not static and subject to change.

因此,我需要一些方法来从.lua文件中导入函数,或者简单地从Python脚本中使用一些参数执行.lua文件并接收返回值.

Hence, I need some way of importing the functions from the .lua file or simply executing the .lua file from the Python script with some arguments and receive a return value.

有人可以指出我正确的方向吗?

Could someone point me in the right direction?

将不胜感激.

推荐答案

您可以使用subprocess运行Lua脚本并为函数提供参数.

You can use a subprocess to run your Lua script and provide the function with it's arguments.

import subprocess

result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test("a", "b")'])
print(result)

result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test2("a")'])
print(result)

  • -l需要给定的库(您的脚本)
  • -e是应在启动时执行的代码(您的函数)
    • the -l requires the given library (your script)
    • the -e is the code that should be executed on start (your function)
    • result的值将是STDOUT的值,因此只需将返回值写入其中,就可以在Python脚本中简单地读取它.我在该示例中使用的演示Lua脚本仅打印了以下参数:

      The value of result will be the value of STDOUT, so just write your return value to it and you can simply read it in your Python script. The demo Lua script I used for the example simply prints the arguments:

      function test (a, b)
          print(a .. ', ' .. b)
      end
      
      function test2(a)
          print(a)
      end
      

      在此示例中,两个文件必须位于同一文件夹中,并且lua可执行文件必须位于您的PATH上.

      In this example both files have to be in the same folder and the lua executable must be on your PATH.

      仅产生一个Lua VM的另一种解决方案是使用pexpect并以交互模式运行该VM.

      An other solution where only one Lua VM is spawned is using pexpect and run the VM in interactive mode.

      import pexpect
      
      child = pexpect.spawn('lua -i -l demo')
      child.readline()
      
      child.sendline('test("a", "b")')
      child.readline()
      print(child.readline())
      
      child.sendline('test2("c")')
      child.readline()
      print(child.readline())
      
      child.close()
      

      因此,您可以使用sendline(...)向解释器发送命令,并使用readline()读取输出. sendline()之后的第一个child.readline()读取命令将被打印到STDOUT的行.

      So you can use sendline(...) to send a command to the interpreter and readline() to read the output. The first child.readline() after the sendline() reads the line where the command will be print to STDOUT.

      这篇关于从Python运行Lua脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆