Matt Creighton
Matt Creighton

Reputation: 101

directly quoting %~dp0 does not ignore spaces in file path

i have a script which 3 arguments, two of which are paths. I would like to call it from a .bat file.

python myscript.py "%~dp0inputs/" "%~dp0outputs/" "foo"

If i call a dummy script that simply prints argv using the above line, i get the expected results, even for paths containing spaces:

myscript.py
C:\path\containing spaces\inputs/
C:\path\containing spaces\outputs/
foo

however if i use this (ie %~dp0 for argument 1 with nothing else between the quotes):

python myscript.py "%~dp0" "%~dp0outputs/" "foo"

then it behaves oddly when the path contains spaces:

myscript.py
C:\path\containing spaces" C:\path\containing
spaces\outputs/ foo

it seems that the quotes have not been processed properly - what have i done wrong?

Upvotes: 1

Views: 2330

Answers (2)

joeking
joeking

Reputation: 2106

It is because the quotes are passed into the python script. And %~dp0 ends with a \ character.

Python figures that \ escapes the double quote - fun.

So, "%~dp0" is passed to the script as

"C:\temp\containing spaces\"

Python treats that trailing \ as escaping the quote, so it merges the arguments.

It shouldn't do that - but it does.

You can remove the trailing \, or add another. Either of these works:

python myscript.py "%~dp0/" "%~dp0outputs/" "foo"
python myscript.py "%~dp0\" "%~dp0outputs/" "foo"

Upvotes: 3

Gourav
Gourav

Reputation: 116

try to use Set to call your paths within batch. (example below)

@echo off

set myscrpt="C:\path\containing spaces\mypythonscript.py"
set mypath1="C:\path\containing spaces\inputs"
set mypath2="C:\path\containing spaces\outputs"

pushd C:\Python27
Python %myscrpt% %mypath1% %mypath2%
pause>NUL
exit

Upvotes: 0

Related Questions