bat文件在另一个包含Python的文件夹中时未运行
非常简单,我有这个代码bat文件在另一个包含Python的文件夹中时未运行,python,windows,python-2.7,batch-file,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("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和Windows7。我不明白为什么路径会导致此错误
我的test.bat很简单:
echo "test success"
cmd.exe
对不带引号的输入命令行参数执行了一些有趣的操作。详情可在此活动中找到:
在您的例子中,shell在/
处分解字符串,将其视为将传递给蝙蝠的标志的开始。有两个可用选项:
- 使用
\\
分隔路径元素:将“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不同)。如果您感兴趣,请参阅以了解更多详细信息。尝试用反斜杠代替正斜杠:“Bats\\test.bat”
或r“Bats\test.bat”
代替“Bats/test.bat”
。我认为Windows将正斜杠解释为命令行选项的开始。@MadPhysicator,它不是“Windows”而是cmd.exe,它默认为解析“/”作为选项的命令行开关。OP还应该能够使用“Bats/test.bat”
。还请注意,shell=True
不是必需的,因为Windows知道为批处理文件运行cmd.exe。