2015-06-23 20 views
0

我想写一个进程id到文件,每当启动我的程序,所以我编写了这段代码,但是这个代码在每次停止进程时都会写入pid到文件。如何写入python中的多进程文件

from multiprocessing import Process 
from os import getpid 


def f(): 
    file = open('udp.pid', 'w') 
    file.write(str(getpid())) 
    file.close() 
    while True: 
     # a socket infinity loop 
     pass 

if __name__ == '__main__': 
    p = Process(target=f,) 
    p.start() 

如何在多进程中写入pid到文件?

UPDATE:

我用我认为使用多进程与否并不重要窗口8.1

回答

1

蟒蛇3.4。它只是写!

开放(名称[,模式[,缓冲剂]])在https://docs.python.org/2/library/functions.html

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).

变化

代码

file = open('udp.pid', 'w') 

file = open('udp.pid', 'wb', 0) 
+0

我测试了它,并得到这个错误“ValueError:不能有无缓冲的文本I/O” –

+0

什么也没有发生!,我使用python-3.4,我改变'w'到'wb',和'file.write(str getpid()))“to”file.write(str(getpid())。encode('utf-8))“但没有任何改变,程序在结束处理后将文件写入文件! –

+0

我测试了OS X上的代码。它的工作原理!事件你的代码写你的预期pid immediatley。 – han058