Invoking External Programs

os.execute()

os.execute() allows one to execute external programs. The behaviour will differ a little depending on your operating system – Windows/Linux/Unix/Mac OS X etc.

This code snippet shows some of the syntax you can use:

-- Notice the need to enclose a file path with spaces with " characters
-- Plus the need to escape the string correctly.
os.execute('\"C:\\Program files\\iNTERFACEWARE\\Chameleon\\Simulator.exe\"')
-- Windows can also take / separators which makes this syntax work too
os.execute('"C:/Program files/iNTERFACEWARE/Chameleon/Simulator.exe"')

Quite often one needs to chain a few commands together. For instance changing the working directory can be very important. This syntax works:

os.execute('cd C:\\temp && run.bat')

Tip: All os.execute() actions will run in test and live mode. In this example you might want to prevent the simulator from running in live mode.

The solution is simply to use iguana.isTest() to prevent the code from running.

io.popen() [top]

io.popen is helpful in that it allows you to open a command line process and read and write to it.

This shows an example of getting the output from the dir command in the C:\temp\ directory. The dialog comes up by double clicking on the blue string. It’s a good idea to do D:close() after you are finished with reading from the process otherwise it may take a while for the process to be terminated when the Lua garbage collector kicks in.

Workaround if popen() is not available [top]

If popen is not available then this technique might be useful. This shows an example of piping output from a command into a temporary text file called ‘blah.txt’ and then reading it afterwards:

Get current working directory [top]

This is helpful thing to do. The command to use will vary on your OS. Most operating systems have the ‘pwd’ command with the exception of windows for which if you type ‘cd’ it will give you back the current working directory.

Here’s a code snippet that works under windows:

Notice we clip off the \n character and append a \. The single \ character is escaped as two \\ characters.

Leave A Comment?