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

查看:36
本文介绍了从 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 在 Python 中嵌入 Lua 代码,反之亦然的教程,但是,我要在 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天全站免登陆