【问题标题】:Use Popen to execute a Powershell script in Python, how can I get the Powershell script's output and update it to web page?使用 Popen 在 Python 中执行 Powershell 脚本,如何获取 Powershell 脚本的输出并将其更新到网页?
【发布时间】:2011-06-07 19:18:39
【问题描述】:

我用一个按钮创建了一个简单的 HTML。当用户单击该按钮时,它将调用在服务器端执行的 Python 文件。在 Python 文件中,我使用 Popen 调用 Powershell 脚本,如下代码:

command_line = r'"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -psc "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\vim.psc1" -noe -c ". \"C:\DoSth\DoSth.ps1\""'
args = shlex.split(command_line)
sys.stdout.flush()
retcode = subprocess.Popen(args)

但是 Powershell 需要很长时间才能完成(并在执行过程中产生大量输出)。用户点击按钮后,浏览器显示“Waiting for xxx”大约几分钟,直到python代码完全执行。

问题是:如何在执行过程中获取Powershell的输出,并及时更新输出到浏览器?

【问题讨论】:

  • 所以你想实时更新?我的意思是,您希望在subprocess 返回后立即更新
  • @sukhbir:是的,我想实时更新。 Powershell 脚本会打印很多“connected to server1\n”、“connected to server2\n”等输出,希望这些信息能及时在浏览器端更新:当 Powershell 打印“connected to server1\n”时,浏览器也显示“已连接到 server1\n”;然后Powershell打印""connected to server2\n",浏览器也显示"connected to server2\n"...

标签: python powershell


【解决方案1】:

是否可以将stdout 参数用于subprocess.Popen

我的意思是这样的:

retcode = subprocess.Popen(args, stdout=sys.stdout)

【讨论】:

  • 是的。请参阅subprocess 的 Python 文档。
猜你喜欢
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-24
相关资源
最近更新 更多