Windows command processor replaces all environment variable references with syntax %VariableName%
in a command block starting with (
and ending with matching )
during parsing phase of the next command line to execute on which a command block begins. In this case this means all %pythonpath%
in both branches of the IF condition are substituted already by the current value of environment variable pythonpath
before the IF condition is executed at all. This behavior can be seen by running the batch file without @echo off
from within a command prompt window as in this case Windows command processor outputs the command lines after being parsed before execution.
The solution is using delayed expansion as also explained by help of command SET output on running in a command prompt window set /?
on an IF and a FOR example, or avoiding the definition or modification of an environment variable and referencing it once again in same command block.
Here is a solution which works without usage of delayed expansion:
@echo off
set "Separator="
if defined pythonpath if not "%pythonpath:~-1%" == ";" set "Separator=;"
if /I "%username%" == "User42" (
set "pythonpath=%pythonpath%%Separator%C:\src\tensorflow\models\research;C:\src\tensorflow\models\research\object_detection"
) else (
rem Other path is added here to environment variable pythonpath.
)
rem This is common to all users. Variable pythonpath is defined definitely now.
for %%I in ("%CD%") do set "ParentPath=%%~dpI"
set "pythonpath=%pythonpath%;%ParentPath%utils;%ParentPath%mail"
echo %pythonpath%
It additionally makes sure there is not ;;
in value of pythonpath
in case of there is already a semicolon at end. And it makes sure pythonpath
is not defined with a ;
at beginning if this environment variable does not exist at all before first IF condition.
Further there are no relative paths added to pythonpath
because of determining absolute path for ..\utils
and ..\mails
before appending them to pythonpath
.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
if /?
rem /?
set /?
BTW: Invalid labels ::
as comments should not be used in command blocks. That can result in undefined behavior on execution. It is safer to use command REM for comments.