1

Very simply I have this code

 bat_execution = subprocess.Popen("Bats/test.bat", shell=True, stdout=subprocess.PIPE)

which returns the error

'Bats' is not recognized as an internal or external command, operable program, or batch file

However if I move the bat file out of the Bats directory and keep it in the same level as the python code like below, it runs fine:

bat_execution = subprocess.Popen("test.bat", shell=True, stdout=subprocess.PIPE)

I am using python and Windows 7. I do not get why the path is causing this error.

My test.bat is simply:

echo "test success"
user2455869
  • 151
  • 1
  • 13
  • 1
    Try putting a backslash instead of a forward slash: `"Bats\\test.bat"` or `r"Bats\test.bat"` instead of `"Bats/test.bat"`. I think Windows is interpreting the forward slash as the beginning of a command-line option. – Mad Physicist Jul 15 '16 at 15:43
  • 2
    @MadPhysicist, it's not "Windows" but cmd.exe, which defaults to parsing "/" as a command-line switch for options. the OP should also be able to use `'"Bats/test.bat"'`. Also note that `shell=True` isn't necessary since Windows knows to run cmd.exe for a batch file. – Eryk Sun Jul 15 '16 at 15:48

1 Answers1

2

cmd.exe does some interesting things to unquoted input command line arguments. The details can be found in this acticle: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/

In your case, the shell is breaking up the string at the /, treating it as the start of a flag that will be passed to Bats. There are a couple of options available:

  • Use \\ to separate path elements: Change "Bats/test.bat" to "Bats\\test.bat" or r"Bats\test.bat".
  • Quote the input string so that cmd.exe parses it correctly: Change "Bats/test.bat" to '"Bats/test.bat"' or "\"Bats/test.bat\"".

Thanks to @eryksun for the second option.

Also note that shell=True is a) not necessary on Windows, and b) you still need to quote arguments properly even without it (unlike Unix). See the second answer to this question for more details if you are interested.

Community
  • 1
  • 1
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264