langiac
langiac

Reputation: 347

how create process child run method while True in python use multiprocessing?

i want run two process child as

#!/usr/bin/env python
from multiprocessing import Process
import time

def method(namelog):
    filelog  = open(namelog,'w')
    while True:
        time.sleep(0.1)
        filelog.write('test log anything \n')
if __name__ == '__main__':
    p1 = Process(target=method, args=('log1.log',))
    print "start process1"
    p1.start()
    p2 = Process(target=method, args=('log2.log',))
    print "start process2"
    p2.start()

result :

start process1
start process2

program create 2 file log1.log and log2.log
but not save data

i thing process created but it not work help me !!!

Upvotes: 2

Views: 900

Answers (1)

Steinar Lima
Steinar Lima

Reputation: 7821

You have to close your file for writing. Note that I changed the mode in open() from write to append.

Try this:

from multiprocessing import Process
import time

def method(namelog):
    while True:
        with open(namelog,'a') as filelog:
            time.sleep(0.1)
            filelog.write('test log anything \n')
if __name__ == '__main__':
    p1 = Process(target=method, args=('log1.log',))
    print "start process1"
    p1.start()
    p2 = Process(target=method, args=('log2.log',))
    print "start process2"
    p2.start()

Upvotes: 1

Related Questions