阅读输出

时间:2017-01-04 11:41:38

标签: python raspberry-pi subprocess communicate

我使用Gphoto2在数码单反相机上拍照。由于它基于bash命令,我试图使用subprocess.communicate但它在相机拍照后冻结。

如果我在终端中尝试gphoto2 --capture-image-and-download,则需要不到2秒的时间。我正在使用Raspberry Pi。

代码:

import subprocess

class Wrapper(object):

    def __init__(self, subprocess):
        self._subprocess = subprocess

    def call(self,cmd):
        p = self._subprocess.Popen(cmd, shell=True, stdout=self._subprocess.PIPE, stderr=self._subprocess.PIPE)
        out, err = p.communicate()
        return p.returncode, out.rstrip(), err.rstrip()


class Gphoto(Wrapper):
    def __init__(self, subprocess):
        Wrapper.__init__(self,subprocess)
        self._CMD = 'gphoto2'

    def captureImageAndDownload(self):
        code, out, err = self.call(self._CMD + " --capture-image-and-download")
        if code != 0:
            raise Exception(err)
        filename = None
        for line in out.split('\n'):
            if line.startswith('Saving file as '):
                filename = line.split('Saving file as ')[1]
        return filename


def main():
    camera = Gphoto(subprocess)

    filename = camera.captureImageAndDownload()
    print(filname)

if __name__ == "__main__":
    main()

如果我退出,我得到这个:

Traceback (most recent call last):
  File "test.py", line 39, in <module>
   main()
  File "test.py", line 35, in main
    filename = camera.captureImageAndDownload()
  File "test.py", line 22, in captureImageAndDownload
    code, out, err = self.call(self._CMD + " --capture-image-and-download")
  File "test.py", line 11, in call
    out, err = p.communicate()
  File "/usr/lib/python2.7/subprocess.py", line 799, in communicate
    return self._communicate(input)
  File "/usr/lib/python2.7/subprocess.py", line 1409, in _communicate
    stdout, stderr = self._communicate_with_poll(input)
  File "/usr/lib/python2.7/subprocess.py", line 1463, in _communicate_with_poll
    ready = poller.poll()
KeyboardInterrupt

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

根据上述评论,我们提出了这些建议。 .communicate()调用挂起了程序,我怀疑这是因为执行的命令没有正确退出。

可以用来解决这个问题的一件事是手动轮询完成的过程,并随着时间的推移打印输出。
现在上面的要点已写在手机上,所以它没有正确地解决这个问题,但这里有一个示例代码,您可以使用它来捕获输出并手动轮询命令。

import subprocess
from time import time
class Wrapper():
    def call(self, cmd):
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        O = ''
        E = ''
        last = time()
        while p.poll() is None:
            if time() - last > 5:
                print('Process is still running')
                last = time()
            tmp = p.stdout.read(1)
            if tmp:
                O += tmp
            tmp = p.stderr.read(1)
            if tmp:
                E += tmp
        ret = p.poll(), O+p.stdout.read(), E+p.stderr.read() # Catch remaining output
        p.stdout.close() # Always close your file handles, or your OS might be pissed
        p.stderr.close()
        return ret

使用shell=True注意的三件重要事情可能是不好的,不安全的和棘手的 我个人赞成,因为我很少处理用户输入或未知变量&#34;当我执行的东西。但请注意几点 - 永远不要使用它!

其次,如果您不需要分离错误和常规输出,您也可以这样做:

Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

它会让你少担心文件句柄。

最后,始终清空stdout/stderr缓冲区,并始终关闭它们。这两件事很重要 如果您没有清空它们,它们可能会自行挂起应用程序,因为它们已满,Popen无法在其中放入更多数据,因此它会等待您(最好的情况下)场景)清空它们 其次是没有关闭那些文件句柄,这可能会导致你的操作系统用尽可能的文件句柄打开(只有一定数量的集体文件句柄,操作系统可以在任何给定的时间打开,所以不要关闭它们可能会使你的操作系统无用了。)

注意:根据您是否使用Python2或3,p.stdout.read()可能会返回字节数据,这意味着O = ''应为O = b''而不是等)

相关问题