[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: Thijs Schreijer <thijs@...>
- Date: Fri, 30 Aug 2013 07:11:12 +0000
> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On
> Behalf Of Pierre-Yves Gérardy
> Sent: donderdag 29 augustus 2013 23:35
> To: Lua mailing list
> Subject: Re: Shadow shell error messages when running os.execute/io.popen
> from Lua
>
> 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
>
If you use temporary files for stdout and stderr then this penlight [1] code might also provide an implementation
Thijs
[1] https://github.com/stevedonovan/Penlight/blob/master/lua/pl/utils.lua#L221