Compiler directives in the source

Peter Hansen peter at engcorp.com
Thu Feb 6 08:32:34 EST 2003


Alex Martelli wrote:
> 
> Michael Hudson wrote:
>    ...
> >> -x     : skip first line of source
> >
> > I've never understood the purpose of -x.
> 
> I think it's meant to support systems without shebang: in such
> systems you can sometimes write a script such that the first
> line contains all the magic needed to feed the script file
> itself to Python -- but it may be impossible to make that first
> line itself acceptable to Python (e.g. a comment, as in the
> case of the shebang), whence the -x.

As an example from the Windows (or should I say DOS?) world,
a variant (or verbatim?  just going from memory) of something
posted by someone else recently:

----first line of source file follows this line----
@goto dos

python 'Hello, world!'

'''
:dos
@echo off
rem This assumes "python.exe" is in the PATH.
python -x %0.bat %1 %2 %3 %4 %5 %6 %7 %8 %9
rem '''
----last line of source file precedes this line----

The first line uses "@" to prevent echoing the command to stdout,
then does a GOTO (woo-hoo!  there's still a use for them! ;-)
to the line labelled ":dos".

After that line, echoing is "permanently" disabled, then there's
a helpful comment, then a call to the interpreter with "-x" 
argument and the name of the batch file sent with .BAT added, plus
all remaining arguments (up to the DOS limit... ugh).

The interpreter executes the code starting at line 2, and of course
skips everything in the final doc-comment, then returns.  

DOS continues on from the "python" line, skipping the remark
statement and then terminating.

Very helpful for simple utilities, although so far I haven't found
any way to avoid hardcoding the path to the batch file (even when
it's in the PATH) in front of the %0.bat for real uses...  DOS sucks.

-Peter




More information about the Python-list mailing list