Self-executable scripts

From IronPython Cookbook

(Difference between revisions)

Revision as of 13:19, 28 April 2009

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
# Your IronPython code starts from 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 batch command script. The first line invokes the IronPython interpreter, which will be ideally in your PATH, and passes the name of the file 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. Both worlds are happy.

TOOLBOX
LANGUAGES