Run Lua script from Python

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

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

Hence, I need to import functions from a .lua file somehow, or just execute a .lua file from a Python script with some arguments and get the return value.

Can anyone point me in the right direction?

It would be very grateful.

+3


source to share


1 answer


You can use subprocess

to run your Lua script and provide functions with its 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

    the given library is required (your script)
  • -e

    is the code to be run at startup (your function)

The result value will be the value STDOUT

, so just write your return value and you can just read it in your Python script. The Lua script demo I used for the example just prints the arguments:

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

function test2(a)
    print(a)
end

      



In this example, both files should be in the same folder, and the executable lua

should be in yours PATH

.


Another solution where only one Lua VM is generated is used pexpect

and run the virtual machine interactively.

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()

      

So, you can use sendline(...)

to send a command to the interpreter and readline()

to read the output. The first child.readline()

after sendline()

reads the line in which the command will print on STDOUT

.

+4


source







All Articles