bat文件在Python的另一个文件夹中不运行

很简单,我有这个代码

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

它返回错误

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

但是,如果我将bat文件移出Bats目录,并将其保持在与下面的python代码相同的级别,那么它运行良好:

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

我正在使用Python和Windows 7.我不明白为什么path导致此错误。

我的test.bat很简单:

 echo "test success" 

cmd.exe会对引用的输入命令行参数做一些有趣的事情。 细节可以在这个动作中找到: https ://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/

在你的情况下,shell将在/处分割字符串,将其视为将传递给Bats的标志的开始。 有几个选项可用:

  • 使用\\分隔路径元素:将"Bats/test.bat"更改为"Bats\\test.bat"r"Bats\test.bat"
  • 引用输入字符串,以便cmd.exe正确解析:将"Bats/test.bat"更改为'"Bats/test.bat"'"\"Bats/test.bat\""

感谢@eryksun的第二个选项。

还要注意shell=True是a)在Windows上不是必需的,b)即使没有它也需要引用正确的参数(与Unix不同)。 如果您有兴趣,请参阅第二个回答 这个问题的更多细节。