用Python运行Lua脚本

假设我有一个包含两个函数的 Lua 脚本。我想在 Python 脚本中使用一些参数调用这些函数。

我曾经看过使用 Lunatic Python 在 Python 和 Lua 之间嵌入代码的教程,但是,我想在 Python 脚本中执行的 Lua 函数不是静态的,而是可更改的。

因此,我需要一种方式从 .lua 文件中导入函数,或者仅仅在 Python 脚本中执行 .lua 文件并使用一些参数接收返回值。

能有人指点我一下方向吗?

非常感谢。

点赞
用户1161235
用户1161235

你可以使用subprocess运行你的Lua脚本并提供函数对应的参数。

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是在启动时应该执行的代码(你的函数)

结果的值将是STDOUT的值,所以只需将返回值写入其中,就可以在Python脚本中轻松读取它。我用于示例的演示Lua脚本简单地打印了参数:

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

function test2(a)
    print(a)
end

在这个例子中,这两个文件必须在同一个文件夹中,而lua可执行文件必须存在于你的PATH中。


另一种只生成一个Lua虚拟机进程的解决方案是使用pexpect,并在交互模式下运行VM。

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的行。

2015-06-15 09:41:46