简体   繁体   English

python守护进程,不写入文件

[英]python daemon process, doesn't write to file

I'm using a Multiprocessing.Queue to communicate between my processing processes and my daemon process. 我正在使用Multiprocessing.Queue在处理进程和守护进程之间进行通信。 The daemon takes output from the queue and writes to file in an infinite loop. 守护程序从队列中获取输出,并在无限循环中写入文件。 The file object is opened in the daemon process printToFile itself. 该文件对象在守护进程printToFile本身中打开。

resultqueue = Queue()
p = Process(target = printToFile , args=(resultqueue))
p.daemon = True
p.start()


for si, ei in ranges:
    pr = Process(target = processing , args=(si, ei, resultqueue))
    pr.start()
    processes.append(pr)

for pr in processes:
    pr.join()

My problem is that printToFile doesn't write anything to file, even though it prints to screen, the output it gets from the queue. 我的问题是,即使printToFile不会打印任何内容,即使它打印到屏幕上,也将从队列中获取输出。 When I remove the line, setting it to a daemon process, and manually kill the program using Ctrl+C, everything works fine. 当我删除该行,将其设置为守护进程并使用Ctrl + C手动终止该程序时,一切正常。 Can someone please help me understand what is going on. 有人可以帮我了解发生了什么。 I don't know where to start debugging. 我不知道从哪里开始调试。

I am not using fileObject.close() as the daemon dies when the program finished execution. 当程序完成执行时,守护进程消失,因此我没有使用fileObject.close()。 But I don't think that is the problem, because the program does write to file when I use Ctrl+C without making the process daemon. 但是我不认为这是问题所在,因为当我使用Ctrl + C时,程序确实写入了文件,而没有创建进程守护进程。 Another (maybe unrelated) problem, is that when the file object is not instantiated within printToFile, but is a global, even using Ctrl+C doesn't print the output to file. 另一个(可能不相关)的问题是,当文件对象未在printToFile中实例化但是全局对象时,即使使用Ctrl + C也不会将输出打印到文件中。 But I can live with that. 但是我可以忍受。 But I would still like to understand what's going on. 但是我仍然想了解发生了什么。

Since my guess was successful in comments I would point out what I said. 由于我的猜测在评论中很成功,因此我要指出我的意思。 open() function has third argument - buffering : open()函数具有第三个参数- buffering

The optional buffering argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). 可选的buffering参数指定文件所需的缓冲区大小:0表示未缓冲,1表示行缓冲,任何其他正值表示使用(大约)该大小(以字节为单位)的缓冲区。 A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files . 负缓冲意味着使用系统默认值,通常对tty设备使用行缓冲,而对于其他文件则使用完全缓冲 If omitted, the system default is used . 如果省略, 则使用系统默认值

Passing 0 as third argument you open a file in unbuffered mode so the changes appears there immediately. 传递0作为第三个参数,您将以无缓冲模式打开文件,因此更改将立即显示在该文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM