【问题标题】:Python subprocess.call thread hang, subprocess.popen no hangPython subprocess.call 线程挂起,subprocess.popen 没有挂起
【发布时间】:2014-04-08 20:55:39
【问题描述】:

我正在尝试使用Sikuli 和 Windows 7 上的脚本自动安装特定程序。我需要启动程序安装程序,然后使用 Siluki 逐步完成安装的其余部分。我使用 Python 2.7 做到了这一点

此代码按预期工作,通过创建线程、调用子进程,然后继续主进程:

import subprocess
from threading import Thread

class Installer(Thread):
  def __init__(self):
    Thread.__init__(self)
  def run(self):
    subprocess.Popen(["msiexec", "/i", "c:\path\to\installer.msi"], shell=True)

i = Installer()
i.run()
print "Will show up while installer is running."
print "Other things happen"

i.join()

此代码无法按预期运行。它将启动安装程序,但随后挂起:

import subprocess
from threading import Thread

class Installer(Thread):
  def __init__(self):
    Thread.__init__(self)
  def run(self):
    subprocess.call("msiexec /i c:\path\to\installer.msi")

i = Installer()
i.run()
print "Will not show up while installer is running."
print "Other things happen"

i.join()

我了解 subprocess.call 将等待进程终止。为什么这会阻止主线程继续运行?进程调用后main是否应该立即继续执行?

为什么会有这样的行为差异?

我最近才开始使用线程 C。

【问题讨论】:

  • 也许管理员权限是问题所在。试试 subprocess.call(['runas', '/user:Administrator', 'c:\path\to\installer.msi'])
  • 是否需要在安装命令中添加命令行参数以使其成为静默安装?

标签: python multithreading python-2.7 subprocess


【解决方案1】:

您正在调用 i.run(),但您应该调用的是 i.start()。 start() 在单独的线程中调用 run(),但直接调用 run() 会在主线程中执行。

【讨论】:

  • 我会确保它正在使用 i.start() 并看看它是如何工作的。
  • 您的建议是正确的。当我使用 i.start() 而不是 i.run() 时,subprocess.call 工作正常。
【解决方案2】:

首先。

您需要将命令行参数添加到您的安装命令中以使其成为静默安装。 http://msdn.microsoft.com/en-us/library/aa372024%28v=vs.85%29.aspx 子进程可能挂起,等待永远不会结束的安装进程,因为它正在等待用户输入。

第二个。

如果这不起作用..您应该使用 popen 并进行交流 How to use subprocess popen Python

第三个。

如果这仍然不起作用,您的安装程序挂在某个地方,您应该在那里调试底层进程。

【讨论】:

  • 我会寻找静默安装命令参数。这将使过程更容易。
  • 安装的静默命令运行良好,有助于程序的整体执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
  • 2020-03-13
相关资源
最近更新 更多