繁体   English   中英

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

[英]bat file not running when in another folder with 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对未加引号的输入命令行参数做了一些有趣的事情。 可以在此Acticle中找到详细信息: 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)。 如果您有兴趣,请参阅此问题 的第二个答案以获取更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM