gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:55:04 25 4
gpt4 key购买 nike

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

我提出了一对“快速又肮脏”的解决方案:

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

###

最佳答案

您可以尝试创建一个既是python又是windows 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 """

它与您所做的类似,但具有更符合要求的双脚本支持。

关于python - "Bootstrap"Windows shell 中没有 .py/.pyw 关联的 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2472558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com