【问题标题】:Run Another batch file in a batch file using python subprocess mode使用python子进程模式在批处理文件中运行另一个批处理文件
【发布时间】:2017-11-01 11:32:45
【问题描述】:

我想在 C:\Users\Administrator\Desktop 的位置运行一个名为 Mainfile.bat 的 bat 文件

Mainfile.bat 内容

start cmd /k call C:\Users\Administrator\Desktop\1.bat

start cmd /k call C:\Users\Administrator\Desktop\2.bat

start cmd /k call C:\Users\Administrator\Desktop\3.bat

一旦 Mainfile.bat 启动,它应该运行 bat 文件中指定的三个 bat 文件。

要做的是,我用python写了一个代码,

subprocess.call("C:\\Users\\Administrator\\Desktop\\Mainfile.bat",stdin=None, stdout=None, stderr=None, shell=False)

print "Finished"

预期输出:

我想要的是,如果我运行 Mainfile.bat 文件,它应该执行命令。也就是说,Mainfile.bat 中的每个 bat 文件都需要一些时间来完成该过程,一旦完成,它将自动关闭。 仅在运行完所有这些 bat 文件(1.bat、2.bat、3.bat)之后——我需要在控制台中打印“完成”。

实际输出:

但是,一旦它运行 Mainfile.bat 文件,它会执行三个 bat 文件并立即在控制台中打印“完成”。我怎样才能达到预期的输出?

得到预期的输出:

通过更改 Mainfile.bat 中的内容

(
  start 1.bat
  start 2.bat
  start 3.bat
) | pause

echo done!

【问题讨论】:

  • 试试shell=True?也许如果你指定通过 shell 执行,它会阻塞直到 shell 关闭。
  • @cᴏʟᴅsᴘᴇᴇᴅ 不,我试过了,它不起作用
  • 您不需要将 CALL 与 START 命令一起使用。那不会解决你的问题。只是让您知道代码不是必需的。

标签: python batch-file subprocess


【解决方案1】:
    my_process = subprocess.Popen(os.path.abspath('C:\\Users\\Administrator\\Desktop\\Mainfile.bat'), shell=True)
    stdout, stderr = my_process.communicate()
    my_process.wait()

您可以使用communicate(),它会等到进程完成执行。

【讨论】:

  • 这也不行,它的打印立即完成。
  • @pavithranG 你可以试试wait()
  • 所有批处理文件将控制权释放回主批处理文件。因此,您要么监视三个批处理文件的完成执行,要么对批处理文件进行编码,以便在所有三个批处理文件都完成之前,它不会将控制权释放回主批处理文件。
  • @Squashman,我试过像你说的“监控三个批处理文件的完成执行”..它工作得很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多