py2bat (was: How do I make a Python .bat executable file?)

Christian Schaller Christian.Schaller at mchp.siemens.de
Tue Jan 4 12:10:09 EST 2000


Hello...

  I was just reading the above thread and didn't find any program to do
this task automatically.  However, there exists a similar tool for perl,
so I took a closer look at that one.

  After some experiments I came up with a solution that suits for my
needs.  Please don't tell me that anyone else has done that already, I
couldn't find anything on python.org.  Any comments, suggestions?

bye
  Chris...

script starts below
----------------------------------------------------------------------
# name: py2bat.py
# version: 0.1(alpha), Jan/04/2000
#
# description: generate .bat files from python files
# usage: py2bat [-h|-?]
#    or: py2bat [files]
#
# at first, create .bat file for py2bat.py:
#   python py2bat.py py2bat.py
#
# warning: dont use extension (.bat) for executing files generated
# by py2bat.
#
# author: Christian Schaller (Christian.Schaller at mchp.siemens.de),
#         inspired by pl2bat

import sys
import os.path
import getopt

_part1 = '''@echo off
rem="""
if "%OS%" == "Windows_NT" goto WinNT
python -x "%0".bat %1 %2 %3 %4 %5 %6 %7 %8 %9
goto endofpython
:WinNT
python -x "%0".bat %*
if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofpython
if %errorlevel% == 9009 echo ERROR: You do not have Python in your PATH.
goto endofpython
rem """

# python script starts here
'''

# for generating py2bat.bat pay attention to :endofpython to ensure the
shell
# jumping to the right label
_part2 = '\n# end of python script\nrem="""\n:endofpython\nrem """'

_usage = '''Usage: py2bat [-h|-?]
   or: py2bat [files]
       -h or -?  show this help'''

try:
    opts, fileargs = getopt.getopt(sys.argv[1:], '?h')
except getopt.error, e:
    print e
    print _usage
    sys.exit()

for switch, value in opts:
    if switch == '-h' or switch == '-?':
        print _usage
        sys.exit()

# mark for stdin, when no filename is given
if fileargs == []:
    fileargs = ['-']

for filearg in fileargs:
    # should script read from stdin?
    if filearg == '-':
        file = sys.stdin
        # write result to stdout
        out = sys.stdout
    else:
        # filename was given, so we can use that file name
        # for creating the .bat file
        file = open(filearg)
        root, ext = os.path.splitext(filearg)
        if ext == '.py':
            outfile = root + '.bat'
        else:
            outfile = root + ext + '.bat'
        print 'generating', outfile
        out = open(outfile, 'w')

    out.write(_part1)

    while 1:
        line = file.readline()
        if line == '':
            break
        out.write(line)

    file.close()
    out.write(_part2)
    out.close()



More information about the Python-list mailing list