2010-03-18 40 views
7

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

我想出了一对 'quick'n脏' 的解决方案:

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

### 
+0

我没有看到你的第二个解决方案有什么问题(除了'||'应该是'|')。这不是超级优雅,但它完成了工作。 – 2010-03-18 19:03:58

+0

错字,更正,thx。 – PabloG 2010-03-18 19:13:16

回答

9

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

pylint.bat文件从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 """ 

它类似于你做了什么,但有更多的符合dual-script支持。

+0

好的,rem =“”“技巧!我在找什么,thx – PabloG 2010-03-18 19:20:29

+2

这种类型的程序被称为polyglot(http://en.wikipedia.org/wiki/Polyglot_%28computing%29)。 – 2010-03-18 21:38:30

+0

为什么'@echo off'触发a语法错误异常? – 2010-05-31 15:16:34

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目录中......但是这种依赖性已经存在于目标机器上的可能性很高。

+0

我应该提到,我不想冻结脚本,因为我的主要目的是像使用类固醇的“shell程序”一样使用它,保持它容易编辑和修改 – PabloG 2010-03-18 19:12:37