Troubleshooting Errors When Running os.execute()

Introduction

When you use os.execute() to run external commands using you get numeric return codes which are not very helpful. To overcome this issue we have created a module that you can use to provide more descriptive return codes.

There are two versions of this module one Windows systems, and another for Posix systems (Linux, Unix, Mac etc).  The only difference between Windows and Posix is a different mapping for the os.execute() return codes (because Windows and Posix return different numeric codes from os.execute).

There are two options:

  • Map the os.execute numeric return codes to meaningful descriptive text
  • Return the output from the command/script/program that you are running

Task [top]

How to return descriptive codes for the os.execute() command.

Implementation [top]

The repository example code below will return more descriptive returns or return the value of command execution.
Note: The screenshots shown are for Windows — the Posix versions are very similar.

  1. Windows: Import the Run a program under Windows channel from the builtin Iguana Files repository.
  2. Posix: Import the Run a program on POSIX channel from the builtin Iguana Files repository.
  3. Review the main.lua and investigate how the Execute() and ExecuteWithOutput() functions are used in the main() function.
    • The Execute() function maps the os.execute() return code numbers to meaningful messages:
      os.execute code mappings
      Note: These are the Windows code mappings — Posix uses different mappings.
    • Whereas the ExecuteWithOutput() function returns the output from the command:os.execute() with returns

Note: The two example functions are included in the main module (main.lua) for simplicity of presentation. When you are using these functions in your code you should place them in a local or shared module.

How it works [top]

Running the functions in the module for calling command line scripts will give you more descriptive return code. There are two versions of the module: One for Windows and one for Posix, the only difference is in the mapping of the os.execute() return codes.

There are two functions:

  1. Execute(): This function wraps os.execute() and maps the return to descriptive messages.
  2. ExecuteWithOutput(): This function wraps io.popen() and returns the output from the command/script/program that you are running.

More information [top]

Leave A Comment?