【问题标题】:Running a batch file in another directory in python在 python 的另一个目录中运行批处理文件
【发布时间】:2015-11-28 07:06:20
【问题描述】:

我想运行位于与当前目录不同的 MyFolder 中的 mybat.bat 文件。我使用了以下代码:

subprocess.Popen(["mybat", MyArg],
                  cwd=MyFolder,
                  stdout=subprocess.PIPE,
                  stderr=subprocess.PIPE,
                  stdin=subprocess.PIPE)

但是,我收到以下错误:

"WindowsError: [Error 2] The system cannot find the file specified"

我应该提到,如果我用 PATH 中的另一个程序(例如 notepad)替换 mybat,它绝对可以正常工作。

【问题讨论】:

  • 是的。我的文件夹中有 mybat.bat 文件。

标签: python windows batch-file subprocess


【解决方案1】:

工作目录仅在子进程中更改,即cwd=MyFolder 不会使os.path.join(MyFolder, "mybat.bat") 可用。试试:

p = Popen([os.path.join(MyFolder, "mybat.bat"), MyArg], cwd=MyFolder)

你可以用use %~dp0 inside your bat-file, to get the directory where the bat-file resides 代替cwd=MyFolder 作为@eryksun suggested

【讨论】:

  • 谢谢塞巴斯蒂安。您的解决方案也解决了问题。
  • 一个正确编写的批处理文件通常不需要设置cwd 来查找与其自身相关的文件。它应该使用%~dp0 来获取批处理文件的完全限定路径,即.bat 文件的[d]rive 和[p]ath(命令行参数0)。
【解决方案2】:

在命令中添加 shell=True 解决了这个问题。

【讨论】:

猜你喜欢
  • 2021-11-18
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多