从同一个批处理文件中读取批处理文件的第一行? [英] Read the first line of batch file from the same batch file?

查看:59
本文介绍了从同一个批处理文件中读取批处理文件的第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个批处理文件,试图运行其第一行中指定的程序.类似于 Unix 的 shebang:

I have a batch file that tries to run the program specified in its first line. Similar to Unix's shebang:

C:\> more foo.bat
#!C:\Python27\python.exe
%PYTHON% foo-script.py
C:\>

我想知道的是:有没有办法自动%PYTHON%设置为C:\Python27\python.exe在shebang (#!) 之后的脚本的第一行中指定哪个?

What I want to know is: is there a way to automatically set %PYTHON% to C:\Python27\python.exe which is specified in the first line of the script following the shebang (#!)?

背景:我试图这样做,以便在包装器脚本中明确指定要调用的 Python 解释器(因为系统上安装了多个 Python 解释器).

Background: I am trying to do this so as to explicitly specify the Python interpreter to invoke (as there are multiple Python interpreters installed on the system) in the wrapper script.

假设:您可以假设脚本已经知道它自己的文件名 (foo) 和 %~dp0 是目录这个脚本.我们如何阅读不包括shebang的第一行?

Assumption: You can assume that script already knows it's own filename (foo) and %~dp0 is the directory of this script. How do we read the first line excluding the shebang?

澄清:将 C:\PythonXY 添加到 %PATH% 不是解决方案.shebang 行应该在安装时修改(原始脚本仅在构建机器上生成)在用户机器上.. 可能有多个相同版本的 Python 安装.并且只有 shebang 行是可修改的(这就是程序的工作方式).

Clarification: Adding C:\PythonXY to %PATH% is not a solution. The shebang line is supposed to be modified during install time (the original script is generated on the build machine only) on the user's machine .. which may have multiple Python installations of the same version. And only the shebang line is modifyable (that is how the program works).

推荐答案

首先,在windows上,不需要shebang.最好将 Python 解释器的路径包含到运行脚本的用户的 PATH 环境变量中.也就是说,要批量获取第一行,您可以使用 set

Firstly , on windows, there is no need for shebang. Its best to include the path of the Python interpreter to the PATH environment variable of the user who is running the script. That said, to get the first line in batch, you can use set

set /p var=<file

既然你有多个版本的解释器,为什么不在调用脚本时使用正确的一个?

since you have multiple version of interpreter, why not just use the correct one when you invoke the script?

c:\python27\bin\python.exe myscript.py

@echo off
set /p var=<test.py
call %var:~2% test.py

输出

C:\test>more test1.py
#!c:\Python26\python.exe

print "hello"


C:\test>more test.bat
@echo off
set /p var=<test1.py
call %var:~2% test1.py

C:\test>test.bat
hello

这篇关于从同一个批处理文件中读取批处理文件的第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆