读取输出时Python子进程通信冻结

Den*_*nis 0 python subprocess communicate raspberry-pi

我正在使用 Gphoto2 在 DSLR 上拍照。由于它基于我尝试使用的 bash 命令,subprocess.communicate但在相机拍照后它会冻结。

如果我gphoto2 --capture-image-and-download在终端中尝试它需要不到 2 秒。我正在研究树莓派。

代码:

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()
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Tor*_*xed 5

根据上面的评论,这就是我们的想法。该.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
Run Code Online (Sandbox Code Playgroud)

要注意三件重要的事情,使用shell=True可能是不好的、不安全的和棘手的。
我个人喜欢它,因为我在执行东西时很少处理用户输入或“未知变量”。但有几句话要注意 - 永远不要使用它!

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

Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Run Code Online (Sandbox Code Playgroud)

它会让您少担心一个文件句柄。

最后一点,总是清空stdout/stderr缓冲区,并始终关闭它们。这两件事很重要。
如果您不清空它们,它们本身可能会挂起应用程序,因为它们已满并且Popen无法在其中放置更多数据,因此它将等待您(在最佳情况下)清空它们。
其次是不关闭这些文件句柄,这可能会使您的操作系统用完可能的文件句柄来打开(操作系统在任何给定时间只能打开一定数量的集体文件句柄,因此不关闭它们可能会使您的操作系统暂时没用)。

注意:取决于您使用的是 Python2 还是 3,p.stdout.read()可能会返回字节数据,意思O = ''应该是O = b''等)