很简单,我有这个代码
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不同)。 如果您有兴趣,请参阅第二个回答 这个问题的更多细节。