使用Python在另一个文件夹中时,bat文件没有运行

时间:2016-07-15 15:40:54

标签: python windows python-2.7 batch-file

很简单,我有这段代码

 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.我不知道路径导致此错误的原因。

我的test.bat很简单:

echo "test success"

1 个答案:

答案 0 :(得分:2)

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不同)。如果您有兴趣,请参阅the second answerthis question了解详情。