Use lua os.execute in windows to launch a program

2019-01-20 09:24发布

I am happily launching a program in a windows system from Lua using

strProgram = '"C:\\Program Files\\Ps Pad\\PSPad.exe"'
strCmd = 'start "" '..strProgram
os.execute(strCmd)

This works correctly, launching the program and the script finishing. How ever it flashes up a command window for a fraction of a second, does any one have a way from Lua to launch a program.

3条回答
爷、活的狠高调
2楼-- · 2019-01-20 09:49

Lua's os.execute command is based on the C standard library "shell" function. In Windows, this function will always create a command window, and it will always halt your current process until the window finishes. The latter also happens in Linux.

There is ultimately no way around this. Not through the Lua standard API. Because Lua needs to be light-weight and platform independent, the API is not allowed to use OS-dependent native APIs.

Your best bet would be to use the Lua Ex-Api module. It is effectively abandonware, and you may need to patch up a few compiler issues (I'm guessing the Windows port wasn't their first priority). But it is a reasonably good way to spawn processes. You can choose to wait until it finishes yourself, or let them run in parallel. And it won't throw up a command prompt window, unless the application itself uses one.

查看更多
The star\"
3楼-- · 2019-01-20 09:53

This is the piece of code I use to call a batch from Lua, maybe help. In win console (command prompt) open and execute, same in unix (mac|nix)

-- sBatchFile = .bat for windows, .sh for x
function vfFork2(sBatchFile)
    local b = package.cpath:match("%p[\\|/]?%p(%a+)")
    if b == "dll" then 
        -- windows
        os.execute('start cmd /k call "'..sBatchFile..'"')
    elseif b == "dylib" then
        -- macos
        os.execute('chmod +x "'..sBatchFile..'"')
        os.execute('open -a Terminal.app "'..sBatchFile..'"')
    elseif b == "so" then
        -- Linux
        os.execute('chmod +x "'..sBatchFile..'"')
        os.execute('xterm -hold -e "'..sBatchFile..'" & ')
    end 
end 
查看更多
【Aperson】
4楼-- · 2019-01-20 09:53

This is a way to run a command without a console window using only the Lua standard API (i.e. no extra libraries). Tested on Win7 x64.

function exec_silent(command)
    local p = assert(io.popen(command))
    local result = p:read("*all")
    p:close()
    return result
end

Edit: see the comments below, it might not work for everyone. I'm not sure why.

查看更多
登录 后发表回答