How to execute an external command?
The simplest way is os.execute
which works like the C system
call; it calls out to the shell to execute shell commands and external programs. The return code of the execution is usually zero for success.
io.popen
calls a command but returns a file object so you can read the output of the command, if the second argument is 'r', but you can also pass input to a command with a second argument of 'w'. Unfortunately, you don't get a io.popen2
, and you don't get the return code.
There are also two serious weaknesses of these two functions when operating in Windows GUI mode; (a) you will get the dreaded black box flashing from os.execute
and (b) io.popen
just doesn't work.
A way around this is to use COM via LuaCOM. This is part of Lua for Windows
LuaCOM allows you to access the Windows Scripting Host (WSH) objects. The Run
method is documented here
> require 'luacom'
> sh = luacom.CreateObject "WScript.Shell"
> = sh:Run ('cmd /C dir /B > %TMP%\\tmp.txt',0)
The last argument hides the window that would otherwise be generated.
Another more lightweight option is using Winapi.
Be careful using os.tmpname
on Windows; it will not return a full path to a temporary file; for that you need to prepend the value of the %TMP%
environment variable. This used to be merely irritating, since a lot of temporary files ended up in the drive root, but under Vista this is frequently inaccessible (for good reasons).