Python 3 uses multiprocessing and multithreading to check network status

Keywords: network encoding Windows Firefox

Demand setting:
The broadband at home is very unstable recently. When the master comes to visit, he always feels that there is a problem. Write a script, every N seconds to connect the network, to see if there is a drop.

Implementation plan:
python3, using requests library online,
Use the self-contained logging module and write it to the logging.log file if the connection is not available
In order to experiment with multiple processes, a sub process was specially started for networking:
Parent process: start the child process and get messages from the child process. Because the method of getting messages from the child process is blocked, you need to start a thread separately to log the received messages
Subprocess: every N seconds, when the network is connected, it will send a message to the main process. Start a thread at the same time to receive messages related to the main process
In process communication, pipe() returns a pair of connection objects, representing both ends of the pipe. Each object has send() and recv() methods.

The code is as follows:
 

 # -*- encoding:utf-8 -*-
import requests
import multiprocessing
import time
import threading
import logging
import os

#Initialize Log and record Log to
def iniLog():
    logfile = 'logging.log'
    log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'

    #todox jeig support utf8 encode
    handler = logging.FileHandler(logfile, "a",encoding = "UTF-8")
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)
    root_logger = logging.getLogger()
    root_logger.addHandler(handler)
    root_logger.setLevel(logging.INFO)


#Subprocess receiving messages
def recv_message_child(conn):
    while True:
        print('Subprocess waiting for message')
        print('Get news:'+conn.recv())

#Message received by parent process
def recv_message_parent(conn):
    while True:
        print('Parent process waiting for message')
        print('Get news:'+conn.recv())
        logging.info(conn.recv())

#Time interval in seconds between attempts to network
TRY_TIME_SPACE_SECCOND = 15

#Subprocess monitoring network, visit Baidu every try time space seccond seconds
def checkNet_process(conn):
    #Print process number
    print("Current process ID: %s,Parent process ID:%s" % (os.getpid(),os.getppid()))
    # A child process starts a thread to receive messages from the parent process
    t = threading.Thread(target=recv_message_child,args=(conn,))
    t.setDaemon(True)
    t.start()
    #t.join()



    headers={
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
    }
    while True:
        print('child process is running')
        try:
            response = requests.get('http://www.baidu.com',headers=headers)

            print('Return code:'+str(response.status_code))
            print(type(response.status_code))
            if response.status_code != 200:
                #do some task
                print('+++++++++++++++++++++++++++++++++++++++Network unreachable, status code:{0}'.format(response.status_code))
                conn.send('Network unreachable, status code:{0}'.format(response.status_code))
            else:
                print('Normal network access')
        except Exception as e:
            print('Network abnormal error')
            conn.send('Network error reporting:'+str(e))
        finally:
            time.sleep(TRY_TIME_SPACE_SECCOND)



if __name__ == '__main__':
    iniLog()
    logging.info('net check start!')
    #Open up two ports, both of which can be in and out. If False in brackets, it means one-way communication
    conn_parent,conn_child=multiprocessing.Pipe()    
    p=multiprocessing.Process(target=checkNet_process,args=(conn_child,))  #The subprocess uses the sock et interface to call the checknet ﹣ process function
    p.start()

    #The parent process starts a thread to receive messages from the child process
    t = threading.Thread(target=recv_message_parent, args=(conn_parent,))
    t.setDaemon(True)
    t.start()
    t.join()

Posted by drdapoo on Wed, 15 Apr 2020 09:45:29 -0700