很简单,我有这段代码
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"
答案 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 answer至this question了解详情。