[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Shadow shell error messages when running os.execute/io.popen from Lua
- From: Pierre-Yves Gérardy <pygy79@...>
- Date: Thu, 29 Aug 2013 23:35:03 +0200
You could try something like this (modified from either another lua-l
post or the Wiki, I don't remember):
function execute(command)
-- returns success, error code, output.
local f = io.popen(command..' 2>&1 && echo " $?"')
local output = f:read"*a"
local begin, finish, code = output:find" (%d+)\n$"
output, code = output:sub(1, begin -1), tonumber(code)
return code == 0 and true or false, code, output
end
success, code, output = execute"ls -lA"
Both stdout and stderr end up intertwined in the "output" variable.
It is a bit of a hack, but it works. The key lies in this line:
local f = io.popen(file..' 2>&1 && echo " $?"')
which redirects stderr to stdout, and appends the exit code ("$?") to
the output.
A similar method can be used in Windows. I didn't implement it and I
don't remember the details, but here's the gist of it.
It can't be done using only the stadard "cmd" shell (the one called by
io.popen) because the equivalent of "$?" is evaluated before the
command is run, and it returns the exit code of the previous process.
You have to invoke the PowerShell passing it the command encoded in
Base 64 (and first pre-process the command to extract the exit code,
just like in the function above).
-- Pierre-Yves
-- Pierre-Yves
On Thu, Aug 29, 2013 at 7:04 PM, Ousmane Roland Yonaba
<roland.yonaba@gmail.com> wrote:
> Hi community,
>
> It is known that one can execute shell commands via Lua's native os.execute,
> or io.open.
> I am willing to get the output of a specific command. This command is
> supposed to return an output, but can also fairly err, depending on the user
> configuration.
>
> The thing is, when we actually input a wrong command in a shell output, it
> prints an an error message readily, while still running the Lua program.
> Well, is it possible to somehow shadow that error message ? Catching the
> output, redirecting it somewhere else, and then display (or not) a
> custom-made report instead ? If so, can I have some pointers, in terms of
> code ?
>
> As I am horrible at stating things in simple and few words (I do admire
> native english-speaking people conciseness), I can come up with an example,
> if needed.
>
>
> Best regards,
> Roland Y.