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?
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.
In your second example, the main
function references my_file
which is not in that function's scope.
def main():
my_file.write("Daemon creation was successful")
my_file.close()
That function will (if your example is complete) raise a NameError
for the my_file
name.
One way to correct that is to make my_file
a parameter of main
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.