[英]how to write to file in multiprocess in python
I want to write a process id to file whenever start my program, so I wrote this code, but this code write pid to file whenever stop the process. 我想在每次启动程序时都将进程ID写入文件,所以我编写了此代码,但是只要停止进程,此代码就将pid写入文件。
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()
how to write pid to file in multiprocess? 如何在多进程中将pid写入文件?
UPDATE: 更新:
I use python 3.4 on windows 8.1 我在Windows 8.1上使用python 3.4
I think using multiprocess or not does not matter. 我认为使用多进程与否无关紧要。 It just about write!
它只是写!
open(name[, mode[, buffering]]) 打开(名称[,模式[,缓冲]])
in https://docs.python.org/2/library/functions.html 在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).
可选的buffering参数指定文件所需的缓冲区大小: 0表示未缓冲 ,1表示行缓冲,任何其他正值表示使用(大约)该大小(以字节为单位)的缓冲区。
change your code 更改您的代码
file = open('udp.pid', 'w')
to 至
file = open('udp.pid', 'wb', 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.