pythondaemonfunction-callspython-daemon

python-daemon does not work if called by function


I'm trying to use the python-daemon library to spawn a daemon that will write to a file.

When I create the daemon directly in the "if __name__ == '__main__'" statement, the daemon successfully writes to the file:

from daemon import DaemonContext
def main():
    my_file.write("Daemon creation was successful")
    my_file.close()

if __name__ == "__main__":
    my_file = open("my_file", "w+")
    with DaemonContext(files_preserve=[my_file.fileno()]):
        main()

However, when I use a separate function for daemon creation, the daemon does not write to the file:

from daemon import DaemonContext
def main():
    my_file.write("Daemon creation was successful")
    my_file.close()

def create_daemon():
    my_file = open("my_file", "w+")
    with DaemonContext(files_preserve=[my_file.fileno()]):
        main()

if __name__ == "__main__":
    create_daemon()

The if statement in the working example and the "create_daemon" function in the non-working example share the exact same code. Why then, am I unable to create a daemon by calling a function?


Solution

  • This has nothing to do with daemons. main doesn't have access to my_file; you didn't pass the file in as an argument or anything.