开发者

"Bootstrap" python script in the Windows shell without .py / .pyw associations

开发者 https://www.devze.com 2022-12-24 11:44 出处:网络
Sometimes (in customer\'s PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW.

Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW.

I came out with a pair of 'quick'n dirty' solutions:

1)

"""
e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe
goto eof:
""" 
# Python test
print "[works, but shows shell errors]"

2)

@echo off
for /f "skip=4 delims=xxx" %%l开发者_运维技巧 in (%0) do @echo %%l | e:\devtools\python\python.exe
goto :eof
::----------

# Python test
print "[works better, but is somewhat messy]"

Do you know a better solution? (ie: more concise or elegant)


Update:

based on @van answer, the more concise way I found (without setting ERRORLEVEL)

@e:\devtools\python\python.exe -x "%~f0" %* & exit /b

### Python begins....
import sys

for arg in sys.argv:
    print arg

raw_input("It works!!!\n")

###


You can try to create a script what is both python and windows shell script. In this case you can name you file my_flexible_script.bat and execute it either directly or via python ....

See a content of pylint.bat file from pylint:

@echo off
rem = """-*-Python-*- script
rem -------------------- DOS section --------------------
rem You could set PYTHONPATH or TK environment variables here
python -x "%~f0" %*
goto exit

"""
# -------------------- Python section --------------------
import sys
from pylint import lint
lint.Run(sys.argv[1:])


DosExitLabel = """
:exit
exit(ERRORLEVEL)
rem """

It is similar to what you do, but has more compliant dual-script support.


I use the following distutils/py2exe script to produce a single runnable executable file:

from distutils.core import setup
import py2exe, sys, os

sys.argv.append('py2exe')

setup(
    options = {'py2exe': {'bundle_files': 1}},
    console = [{'script': "MyScript.py"}],
    zipfile = None,
)

I see that MSVCR71.DLL gets copied into the dist directory as a result... but the chances are high that this dependancy is already on the target machine.

0

精彩评论

暂无评论...
验证码 换一张
取 消