【问题标题】:bat file not running when in another folder with Python使用 Python 在另一个文件夹中时,bat 文件未运行
【发布时间】:2016-11-18 21:37:56
【问题描述】:

很简单,我有这个代码

 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"

【问题讨论】:

  • 尝试使用反斜杠而不是正斜杠:"Bats\\test.bat"r"Bats\test.bat" 而不是 "Bats/test.bat"。我认为 Windows 将正斜杠解释为命令行选项的开头。
  • @MadPhysicist,它不是“Windows”而是 cmd.exe,它默认将“/”解析为选项的命令行开关。 OP 也应该能够使用'"Bats/test.bat"'。另请注意,shell=True 不是必需的,因为 Windows 知道为批处理文件运行 cmd.exe。

标签: python windows python-2.7 batch-file


【解决方案1】:

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 了解更多详情。

【讨论】:

    猜你喜欢
    • 2010-10-13
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多