0

I've got a python script. Script takes screenshots from web pages. I use xvfb to run it. After about 240 iterations I recieved a message:

"Maximum number of clients reached script.py: cannot connect to X server :99".

I'd like to have more then 3 000 iterations.

Is there any way to close xserver connections without stopping the script do avoid an error?

Script.py has a for loop and uses code from:

webkit.py:

 import sys
 import time
 from PyQt4.QtCore import QUrl
 from PyQt4.QtGui import QApplication, QImage, QPainter
 from PyQt4.QtWebKit import QWebView
 from PyQt4 import QtCore

 class Screenshot(QWebView):

    def __init__(self, width, height):
        self.app = QApplication(sys.argv)
        QWebView.__init__(self)
        self._loaded = False
        self.loadFinished.connect(self.load_finished)
        self.width = int(width)
        self.height = int(height)
        self.app.deleteLater()


    def capture(self, url, output_file):
        self.load(QUrl(url))
        self.wait_load()
        frame = self.page().mainFrame()
        self.page().setViewportSize(QtCore.QSize(self.width, self.height))
        image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
        painter = QPainter(image)
        frame.render(painter)
        painter.end()
        image.save(output_file)

        return output_file

    def wait_load(self, delay=1):
        while not self._loaded:
            self.app.processEvents()
            time.sleep(delay)
        self._loaded = False

    def load_finished(self):
        self._loaded = True
w0jt
  • 1
  • 1
  • Does calling `self.app.exit(0)` in order to delete/dispose of the `QApplication` help? i.e. doing a little bit of your own object lifecycle management. – Anya Shenanigans Aug 11 '15 at 07:49
  • `self.app.exit(0)` Does not help. – w0jt Aug 11 '15 at 10:20
  • It's just that I don't see anywhere that actually finishes off the QApplication object, which is the most likely source of the problem. Perhaps you could refactor to use one `QApplication`, and multiple `QWebView`s? – Anya Shenanigans Aug 11 '15 at 11:00
  • @w0jt. Creating multiple application objects is asking for trouble, and is completely unnecessary. Create **one** global instance of both `QApplication` and `Screenshot`, and then re-use them for every url that needs to be processed. It's also simpler to use signals rather than a for-loop - see [this answer](http://stackoverflow.com/a/21918243/984421) for a working example. – ekhumoro Aug 11 '15 at 16:02
  • @ekhumoro Thank you! That is a perfect answer. I moved instances of `Screenshot` and `QApplication` to my main script before for loop. – w0jt Aug 13 '15 at 07:29

0 Answers0