Self-executable scripts

From IronPython Cookbook

Revision as of 16:23, 28 April 2009 by Snakecharmer (Talk | contribs)

To run IronPython scripts on Windows, you have to ask the IronPython interpreter (ipy.exe) to invoke them. As a result, you need to always type ipy SCRIPT_PATH , which can be rather annoying. To make the scripts self-executable so that you can just type the name and go, you need to simply do two things:

  • Rename the script extension from .py to .cmd or .bat.
  • Make the first line of the script read exactly:
@ipy -x "%~f0" %* & goto :EOF

For example, put the following into a file called hello.cmd:

@ipy -x "%~f0" %* & goto :EOF
# Python code starts from here, second line onwards
import sys
args = sys.argv[1:]
if args:
    print 'You said:', ' '.join(args)
print 'I say, greetings!'

Now you can just type hello and the script runs! The way this works is that the whole script is treated like a Windows shell (batch/command) script. The first line invokes the IronPython interpreter, which will be ideally in your PATH, and passes the absolute path to the file (%~f0) along with all arguments (%*). The -x switch tells the interpreter to skip the first line of the script and bingo! It does not trump on the first line, which is illegal Python code. When the interpreter returns, goto :EOF will make sure that rest of the now-back-to-shell-script is skipped because the Python code makes for illegal shell commands.

Both worlds are hip and happy!


Note: The same technique can be applied to CPython on Windows using the same -x flag.

TOOLBOX
LANGUAGES