简体   繁体   中英

How to execute a linux terminal command from LUAJ?

I want to simply execute a linux terminal command like ls from LuaJ and the result that it will return or anything that returns i want to receive it and will show the names in the Java Gui . I searched but found this but not one with LuaJ .

Is there any function to execute the terminal command from LuaJ ??

There are multiple ways to do this, for one, you can implement it yourself in Java then link it to LuaJ.

LuaFunction command = new OneArgFunction()
{
    public LuaValue call(LuaValue cmd)
    {
        Process p = Runtime.getRuntime().exec("/bin/sh", "-c", cmd.checkstring());
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        int returnCode = p.waitFor();
        return LuaValue.valueOf(returnCode);
    }
}
globals.set("command", command);

Then in Lua:

local code = command("ls");

The problem with actually getting the output of a command is that you can't just have a fixall solution. For all the system knows you could be calling a program which runs for 2 hours generating constant output, which could be an issue, not to mention if the program requires input. If you know you're only going to use certain functions you can make a dirty version of above function to capture the output from the stream and return it all instead of the exit code, just don't use it on other processes that don't return quickly. The other alternative is to create a class that wraps the input and output streams from the process and return a coerced version of that class, and manage the input and output from lua.

Lua does have a function that's part of the OsLib called execute(), if execute doesn't exist in your current environment then in Java call:

globals.load(new OsLib());

Before loading the lua code. the os.execute() function returns the status code, and doesn't return the streams, so no way to get the output there. To get around this you can modify the command to pipe the output to a temp file and open it with the io library (new IoLib() if doesn't exist in current environment).

The other option is to use io.openProcess, which also executes the command and returns a file to read the output from.

Resources:

http://luaj.org/luaj/3.0/api/org/luaj/vm2/lib/OsLib.html

http://luaj.org/luaj/3.0/api/org/luaj/vm2/lib/IoLib.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM