简体   繁体   中英

Read the first line of batch file from the same batch file?

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:\>

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 ( #! )?

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.

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?

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

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

Edit:

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

output

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

Shebangs are only native to the filesystems of Unix/Linux/BSD variants, due to their design and layout, the filesystem knows that when a file begins with a shebang, the filesystem triggers the user's terminal process to invoke the shell based on the shebang, usually /bin/sh . This can be confirmed by browsing through the filesystem routines here .

Edit: Have edited my answer to make it fully clear in the context of the Windows environment.

In short this is not possible under Windows (2000 upwards to Windows 7) as the NTFS lacks such a capability to interpret the contents of the data (NTFS does not care what is in the file), and therefore lack the means of having an exec call to load the shebang script, only .EXE, .DLL, .SYS,.DRV's are catered for, but for a script....

Hope this helps, Best regards, Tom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM