Windows shell中的“Bootstrap”python脚本没有.py / .pyw关联

时间:2010-03-18 18:56:00

标签: python shell

有时(在客户的PC中)我需要一个python脚本在Windows shell中执行,如.CMD或.BAT,但没有与PYTHON / PYTHONW相关联的.py或.pyw扩展名。

我出来了一对'quick'n dirty'解决方案:

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]"

您知道更好的解决方案吗? (即:更简洁或更优雅)


更新

基于@van回答,我找到了更简洁的方法(没有设置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")

###

2 个答案:

答案 0 :(得分:10)

您可以尝试创建pythonwindows shell script的脚本。在这种情况下,您可以将文件命名为my_flexible_script.bat并直接或通过python ...执行。

查看pylintpylint.bat文件内容:

@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 """

它与您的操作类似,但具有更多符合dual-script支持。

答案 1 :(得分:0)

我使用以下distutils / py2exe脚本生成一个可运行的可执行文件:

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,
)

我看到MSVCR71.DLL被复制到dist目录中......但是这个依赖性已经存在于目标机器上的可能性很高。