【问题标题】:Python popen shell command wait till subprocess has finished [duplicate]Python popen shell命令等待子进程完成[重复]
【发布时间】:2016-03-07 23:21:59
【问题描述】:

我知道这个问题之前已经回答过Python popen command. Wait until the command is finished 但问题是我不明白答案以及如何将它应用到我的代码中,所以请不要在没有一点帮助的情况下将这个问题标记为之前提出的问题:)

我有一个函数,它接受一个 shell 命令并执行它并返回变量输出。

它工作正常,只是我不希望控制流继续直到过程完全完成。这样做的原因是我正在使用 imagemagick 命令行工具创建图像,当我尝试访问它们以获取信息时不久,它们是不完整的。这是我的代码..

def send_to_imagemagick(self, shell_command):

    try:
        # log.info('Shell command = {0}'.format(shell_command))
        description=os.popen(shell_command)
        # log.info('description = {0}'.format(description))            
    except Exception as e:
        log.info('Error with Img cmd tool {0}'.format(e))

    while True:
        line = description.readline()
        if not line: break
        return line

非常感谢@Ruben 这是我用来完成它的,所以它可以正确返回输出。

 def send_to_imagemagick(self, shell_command):

        args = shell_command.split(' ')    
        try:                
            description=Popen(args, stdout=subprocess.PIPE)
            out, err = description.communicate()
            return out

        except Exception as e:
            log.info('Error with Img cmd tool {0}'.format(e))

【问题讨论】:

  • 为什么使用os.popen 而不是subprocess.popen?子进程替换 os.popen。我认为你想这样做:description.communicate() 等到它完成。见docs.python.org/2/library/…
  • 那我该怎么写呢?像这样 ...description= subprocess.call([shell_command])
  • return line 将打破while 循环,因为该函数将退出,我认为您应该在这里使用yield line 而不是return。

标签: python subprocess popen imagemagick-convert


【解决方案1】:

使用subprocess.popen:

这个模块打算替换几个旧的模块和功能。

所以在你的情况下import subprocess 然后使用popen.communicate() 等待您的命令完成。

有关这方面的文档,请参阅:here

所以:

from subprocess import Popen

def send_to_imagemagick(self, shell_command):

    try:
        # log.info('Shell command = {0}'.format(shell_command))
        description=Popen(shell_command)
        description.communicate()

        # log.info('description = {0}'.format(description))            
    except Exception as e:
        log.info('Error with Img cmd tool {0}'.format(e))

    while True:
        line = description.readline()
        if not line: break
        return line

【讨论】:

  • 抱歉大写错误:)
  • return line 或 yield line? self 的论点也正确吗?
  • 我不知道,问 OP。
  • 嗯...好吧,没看到您只是复制粘贴 OP 的代码并更改了其中的 os.popen 部分:P
  • 我什至没看过while。看起来很奇怪,我同意这一点。
猜你喜欢
  • 2013-04-03
  • 1970-01-01
  • 2023-04-04
  • 2015-06-13
  • 1970-01-01
  • 2013-07-07
  • 2013-06-15
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多