I’m struggling with improving script which I proposed as an answer to How to write a batch file showing path to executable and version of Python handling Python scripts on Windows? question. To prevent Open With dialog box I’d like to read output of ftype command, extract path of an
executable from it and check if it exists.
After this
@echo off
setlocal EnableDelayedExpansion
rem c:\ftype Python.File ->
rem Python.File="c:\path with spaces, (parentheses) and % signs\python.exe" "%1" %*
for /f "tokens=2 delims==" %%i in ('ftype Python.File') do (
set "reg_entry=%%i"
)
reg_entry's contents is
"c:\path with spaces and (parentheses) and % signs\python.exe" "%1" %*
How do I split this to get
"c:\path with spaces, (parentheses) and % signs\python.exe", "%1" and %*?
EDIT
I tried using call after reading Aacini’s answer and it almost works. It doesn’t handle % sign, however.
@echo off
setlocal EnableDelayedExpansion
set input="c:\path with spaces and (parentheses) and %% signs\python.exe" "%%1" %%*
echo !input!
call :first_token output !input!
echo !output!
goto :eof
:first_token
set "%~1=%2"
goto :eof
Output
"c:\path with spaces and (parentheses) and % signs\python.exe" "%1" %*
"c:\path with spaces and (parentheses) and 1"
An alternative parser that is very similar to the CALL parser is the simple FOR. There are two complicating factors:
1- The FOR must not be expanded while delayed expansion is enabled in case it contains
!. This is easily handled.2- The content must not contain wildcards
*or?. The?can be temporarily substituted for and then returned. But there is no easy way to search and replace*.Since this problem is trying to parse out a path, and paths cannot contain wildcards, this problem is easy to solve without using a CALL. I added
!to the test case for completeness.If we can rely on the fact that the first token will always be enclosed in quotes, then the solution is even easier. We can use FOR /F with both EOL and DELIMS set to
".However, I just looked at my FTYPE output, and discovered some entries were not quoted, even if they contain spaces in the path! I don’t think any of the answers on this page will handle this. In fact the entire premise behind the question may be flawed.