Recipe python daemon package

Martin Zibricky edited this page Sep 25, 2015 · 4 revisions

(Provided by Marcin Barczyński in issue #1108)

When the PyInstaller bootloader begins execution of the main script, there are open file descriptors that point to the executable file itself. By default, the DaemonContext closes all open file descriptors right after the fork. When the script ends, the bootloader tries to close the file descriptors, and the program ends with

close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor

To prevent this, find these file descriptors and note them in the files_preserve value of the context:

import daemon
import psutil
import sys
fds_to_myself = []
if getattr(sys, 'frozen', False):
    fds_to_myself.extend(
        [of.fd for of in  psutil.Process(os.getpid()).open_files() 
            if of.path == sys.executable]
    )
ctx = DaemonContext(
    ...
    files_preserve=fds_to_myself
)