Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

PyQt5: Changing current working directory and restoring, causes image loading bug.



  •     if not os.path.exists(self._workDir):
            os.mkdir(self._workDir)
        curdir = QDir.currentPath()
        QDir.setCurrent(self._workDir)
        while self._renderQueue:
            queue = list(self._renderQueue)
            self._renderQueue.clear()
            for document in queue:
                self.renderDocument(document)
            self.msleep(300)
        QDir.setCurrent(curdir)
    

    That's code of a thread that gets run before startup (and it also is used later, but new threads created).

    Anyway, I'm using QSplashScreen to load an image from /images and that works normally, but only when I change working directory (and then change it back) does it fail.

    My project structure is this:
    [project]
    |
    + images /
    + latex_svg/
    + ( main source code here in project dir)
    + ...
    The above self._workDir that I change to is latex_svg. So I'm assuming the system still thinks we're in there.

    I've tried both Python's os.chdir and PyQt5's QDir approach and both do the same thing.



  • you said thread, not process. different threads within an application will share the same process environment..IOW, the changing working directory is probably not thread-safe. if you truly need to do concurrent workers in different directories then either hardcode the complete paths correctly in your file operations or use instances of processes, not threads.


  • Lifetime Qt Champion

    @enjoysmath You should check the return value of both setCurrent() calls and print out curdir and self._workDir.

    "but only when I change working directory (and then change it back) does it fail" - this is not clear to me. The first setCurrent call succeeds but the second fails?


Log in to reply