Appium + Python3 automatic detection and release port

# ! / Usr / bin / Python the env 
# - * - Coding: UTF-. 8 - * - 
# @time: 2019-08-06 10:38 
# @author: zhouyang 
# @file: check_port.py 
'' ' 
Appium port automatic detection is occupied 
shutdown (self, flag): prohibit receive and send data at a Socket. Using the shutdown () function allows bidirectional data transfer socket becomes unidirectional data transmission, 
shutdown () requires a single parameter that indicates how close the socket 
parameters: 0: Read prohibited in the future; 1: represents a write prohibit future; 2 : that prohibits future reading and writing 

Appium port automatically releases the port is occupied, automatically released 
'' ' 

Import socket
 Import os 

DEF check_port (Host, port):
     ' '' to detect whether the port is occupied '' ' 
    # create a socket object 
    S = socket .socket (socket.AF_INET, socket.

    : 
        S.connect ((Host, Port)) 
        s.shutdown ( 2 )
     the except OSError AS MSG:
         Print ( ' Port Available IS S% ' % Port)
         Print (MSG)
         return True
     the else :
         Print ( ' Port already IS S% use ' % port)
         return False 


DEF relase_port (port):
     ' '' to release the specified port '' ' 
    # Find pid specified port corresponding 
    cmd_find = ' the netstat -aon | the findstr% S '% Port
     Print (cmd_find) 

    # returns the execution result of the command 
    Result = os.popen, (cmd_find) .read ()
     Print (Result) 

    IF STR (Port) and  ' LISTENING '  in Result:
         # Get the pid of the process corresponding to the port 
        i = result.index ( ' LISTENING ' ) 
        Start = I + len ( ' LISTENING ' ) +7 
        End = result.index ( ' \ n- ' ) 
        pid = Result [Start, End] 

        # close the port occupied pid
        cmd_kill='taskkill -f -pid %s'%pid
        print(cmd_kill)
        os.popen(cmd_kill)
    else:
        print('port %s is available'%port)


if __name__ == '__main__':
    host='127.0.0.1'
    port=4725
    # check_port(host,port)
    relase_port(port)

 

Guess you like

Origin www.cnblogs.com/xiuxiu123456/p/11322431.html