Best Python code snippet using Airtest
main.py
Source:main.py  
1import time2import random3import pygame4pygame.init()5display_width = 8006display_height = 6007gameDisplay = pygame.display.set_mode((display_width, display_height))8icon = pygame.image.load("ic.jpg")9pygame.display.set_icon(icon)10wheat=(245, 222, 179)11white = (255, 255, 255)12black = (0, 0, 0)13blue = (0,158,255)14red = (255, 11, 92)15light_red = (188, 0, 47)16yellow = (255, 241, 107)17light_yellow = (255, 242, 133)18green = (111, 255, 101)19light_green = (190, 255, 116)20clock = pygame.time.Clock()21tankWidth = 4022tankHeight = 2023turretWidth = 524wheelWidth = 525ground_height = 3526smallfont = pygame.font.SysFont("comicsansms", 25)27medfont = pygame.font.SysFont("comicsansms", 50)28largefont = pygame.font.SysFont("Yu Mincho Demibold", 85)29vsmallfont = pygame.font.SysFont("Yu Mincho Demibold", 25)30def score(score):31    text = smallfont.render("СÑеÑ: " + str(score), True, white)32    gameDisplay.blit(text, [0, 0])33def text_objects(text, color, size="small"):34    if size == "small":35        textSurface = smallfont.render(text, True, color)36    if size == "medium":37        textSurface = medfont.render(text, True, color)38    if size == "large":39        textSurface = largefont.render(text, True, color)40    if size == "vsmall":41        textSurface = vsmallfont.render(text, True, color)42    return textSurface, textSurface.get_rect()43def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size="vsmall"):44    textSurf, textRect = text_objects(msg, color, size)45    textRect.center = ((buttonx + (buttonwidth / 2)), buttony + (buttonheight / 2))46    gameDisplay.blit(textSurf, textRect)47def message_to_screen(msg, color, y_displace=0, size="small"):48    textSurf, textRect = text_objects(msg, color, size)49    textRect.center = (int(display_width / 2), int(display_height / 2) + y_displace)50    gameDisplay.blit(textSurf, textRect)51def tank(x, y, turPos):52    x = int(x)53    y = int(y)54    possibleTurrets = [(x - 27, y - 2),55                       (x - 26, y - 5),56                       (x - 25, y - 8),57                       (x - 23, y - 12),58                       (x - 20, y - 14),59                       (x - 18, y - 15),60                       (x - 16, y - 17),61                       (x - 13, y - 19),62                       (x - 11, y - 21)63                       ]64    pygame.draw.circle(gameDisplay, blue, (x, y), int(tankHeight / 2))65    pygame.draw.rect(gameDisplay, blue, (x - tankHeight, y, tankWidth, tankHeight))66    pygame.draw.line(gameDisplay, blue, (x, y), possibleTurrets[turPos], turretWidth)67    pygame.draw.circle(gameDisplay, blue, (x - 15, y + 20), wheelWidth)68    pygame.draw.circle(gameDisplay, blue, (x - 10, y + 20), wheelWidth)69    pygame.draw.circle(gameDisplay, blue, (x - 15, y + 20), wheelWidth)70    pygame.draw.circle(gameDisplay, blue, (x - 10, y + 20), wheelWidth)71    pygame.draw.circle(gameDisplay, blue, (x - 5, y + 20), wheelWidth)72    pygame.draw.circle(gameDisplay, blue, (x, y + 20), wheelWidth)73    pygame.draw.circle(gameDisplay, blue, (x + 5, y + 20), wheelWidth)74    pygame.draw.circle(gameDisplay, blue, (x + 10, y + 20), wheelWidth)75    pygame.draw.circle(gameDisplay, blue, (x + 15, y + 20), wheelWidth)76    return possibleTurrets[turPos]77def rival_tank(x, y, turPos):78    x = int(x)79    y = int(y)80    possibleTurrets = [(x + 27, y - 2),81                       (x + 26, y - 5),82                       (x + 25, y - 8),83                       (x + 23, y - 12),84                       (x + 20, y - 14),85                       (x + 18, y - 15),86                       (x + 15, y - 17),87                       (x + 13, y - 19),88                       (x + 11, y - 21)89                       ]90    pygame.draw.circle(gameDisplay, blue, (x, y), int(tankHeight / 2))91    pygame.draw.rect(gameDisplay, blue, (x - tankHeight, y, tankWidth, tankHeight))92    pygame.draw.line(gameDisplay, blue, (x, y), possibleTurrets[turPos], turretWidth)93    pygame.draw.circle(gameDisplay, blue, (x - 15, y + 20), wheelWidth)94    pygame.draw.circle(gameDisplay, blue, (x - 10, y + 20), wheelWidth)95    pygame.draw.circle(gameDisplay, blue, (x - 15, y + 20), wheelWidth)96    pygame.draw.circle(gameDisplay, blue, (x - 10, y + 20), wheelWidth)97    pygame.draw.circle(gameDisplay, blue, (x - 5, y + 20), wheelWidth)98    pygame.draw.circle(gameDisplay, blue, (x, y + 20), wheelWidth)99    pygame.draw.circle(gameDisplay, blue, (x + 5, y + 20), wheelWidth)100    pygame.draw.circle(gameDisplay, blue, (x + 10, y + 20), wheelWidth)101    pygame.draw.circle(gameDisplay, blue, (x + 15, y + 20), wheelWidth)102    return possibleTurrets[turPos]103def game_controls():104    gcont = True105    while gcont:106        for event in pygame.event.get():107            if event.type == pygame.QUIT:108                pygame.quit()109                quit()110        gameDisplay.fill(black)111        message_to_screen("УпÑавление", white, -100, size="large")112        message_to_screen("ÐгонÑ: пÑобел", wheat, -30)113        message_to_screen("ÐеÑемеÑение дÑла: ввеÑÑ
 или вниз ÑÑÑелками", wheat, 10)114        message_to_screen("ÐеÑемеÑение Ñанка: влево или впÑаво ÑÑÑелками", wheat, 50)115        message_to_screen("УдеÑживайÑе D Ð´Ð»Ñ Ð¿Ð¾Ð²ÑÑÐµÐ½Ð¸Ñ % моÑноÑÑи вÑÑÑÑела или Ð Ð´Ð»Ñ Ð¿Ð¾Ð½Ð¸Ð¶ÐµÐ½Ð¸Ñ % ", wheat, 140)116        message_to_screen("ÐаÑза: P", wheat, 90)117        button("ÐгÑаÑÑ", 150, 500, 100, 50, green, light_green, action="play")118        button("ÐÑновное", 350, 500, 100, 50, yellow, light_yellow, action="main")119        button("ÐÑÑ
од", 550, 500, 100, 50, red, light_red, action="quit")120        pygame.display.update()121        clock.tick(15)122def button(text, x, y, width, height, inactive_color, active_color, action=None,size=" "):123    cur = pygame.mouse.get_pos()124    click = pygame.mouse.get_pressed()125    if x + width > cur[0] > x and y + height > cur[1] > y:126        pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))127        if click[0] == 1 and action != None:128            if action == "quit":129                pygame.quit()130                quit()131            if action == "controls":132                game_controls()133            if action == "play":134                gameLoop()135            if action == "main":136                game_intro()137    else:138        pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))139    text_to_button(text, black, x, y, width, height)140def pause():141    paused = True142    message_to_screen("ÐаÑза", white, -100, size="large")143    message_to_screen("ÐажмиÑе С, ÑÑÐ¾Ð±Ñ Ð¿ÑодолжиÑÑ Ð¸Ð³ÑÑ Ð¸Ð»Ð¸ Q Ð´Ð»Ñ Ð²ÑÑ
ода из нее", wheat, 25)144    pygame.display.update()145    while paused:146        for event in pygame.event.get():147            if event.type == pygame.QUIT:148                pygame.quit()149                quit()150            if event.type == pygame.KEYDOWN:151                if event.key == pygame.K_c:152                    paused = False153                elif event.key == pygame.K_q:154                    pygame.quit()155                    quit()156        clock.tick(5)157def barrier(x_location, random_Height, barrier_width):158    pygame.draw.rect(gameDisplay, green, [x_location, display_height - random_Height, barrier_width, random_Height])159def explosion(x, y, size=50):160    burst_up = True161    while burst_up:162        for event in pygame.event.get():163            if event.type == pygame.QUIT:164                pygame.quit()165                quit()166        startPoint = x, y167        colorChoices = [red, light_red, yellow, light_yellow]168        magnitude = 1169        while magnitude < size:170            burst_up_bit_x = x + random.randrange(-1 * magnitude, magnitude)171            burst_up_bit_y = y + random.randrange(-1 * magnitude, magnitude)172            pygame.draw.circle(gameDisplay, colorChoices[random.randrange(0, 4)], (burst_up_bit_x, burst_up_bit_y),173                               random.randrange(1, 5))174            magnitude += 1175            pygame.display.update()176            clock.tick(100)177        burst_up = False178def fireShell(x_y, tankx, tanky, turPos, shot_power, x_location, barrier_width, random_Height, rival_Tank_X, rival_Tank_Y):179    fire = True180    damage = 0181    startingShell = list(x_y)182    print("ÐгонÑ!", x_y)183    while fire:184        for event in pygame.event.get():185            if event.type == pygame.QUIT:186                pygame.quit()187                quit()188        pygame.draw.circle(gameDisplay, red, (startingShell[0], startingShell[1]), 5)189        startingShell[0] -= (12 - turPos) * 2190        startingShell[1] += int(191            (((startingShell[0] - x_y[0]) * 0.015 / (shot_power / 50)) ** 2) - (turPos + turPos / (12 - turPos)))192        if startingShell[1] > display_height - ground_height:193            print("ÐоÑледнее пÑобиÑие:", startingShell[0], startingShell[1])194            hit_x = int((startingShell[0] * display_height - ground_height) / startingShell[1])195            hit_y = int(display_height - ground_height)196            print("УÑон:", hit_x, hit_y)197            if rival_Tank_X + 10 > hit_x > rival_Tank_X - 10:198                print("ÐÑиÑиÑеÑкое попадание!")199                damage = 25200            elif rival_Tank_X + 15 > hit_x > rival_Tank_X - 15:201                print("СилÑнÑй вÑÑÑÑел!")202                damage = 18203            elif rival_Tank_X + 25 > hit_x > rival_Tank_X - 25:204                print("СÑедний вÑÑÑÑел")205                damage = 10206            elif rival_Tank_X + 35 > hit_x > rival_Tank_X - 35:207                print("Ðегкий вÑÑÑÑел")208                damage = 5209            explosion(hit_x, hit_y)210            fire = False211        check_x_1 = startingShell[0] <= x_location + barrier_width212        check_x_2 = startingShell[0] >= x_location213        check_y_1 = startingShell[1] <= display_height214        check_y_2 = startingShell[1] >= display_height - random_Height215        if check_x_1 and check_x_2 and check_y_1 and check_y_2:216            print("ÐоÑледнее пÑобиÑие:", startingShell[0], startingShell[1])217            hit_x = int((startingShell[0]))218            hit_y = int(startingShell[1])219            print("УÑон:", hit_x, hit_y)220            explosion(hit_x, hit_y)221            fire = False222        pygame.display.update()223        clock.tick(60)224    return damage225def e_fireShell(x_y, tankx, tanky, turPos, shot_power, x_location, barrier_width, random_Height, ptank_x, ptank_y):226    damage = 0227    flowPower = 1228    power_found = False229    while not power_found:230        flowPower += 1231        if flowPower > 100:232            power_found = True233        fire = True234        start_Shell = list(x_y)235        while fire:236            for event in pygame.event.get():237                if event.type == pygame.QUIT:238                    pygame.quit()239                    quit()240            start_Shell[0] += (12 - turPos) * 2241            start_Shell[1] += int(242                (((start_Shell[0] - x_y[0]) * 0.015 / (flowPower / 50)) ** 2) - (turPos + turPos / (12 - turPos)))243            if start_Shell[1] > display_height - ground_height:244                hit_x = int((start_Shell[0] * display_height - ground_height) / start_Shell[1])245                hit_y = int(display_height - ground_height)246                if ptank_x + 15 > hit_x > ptank_x - 15:247                    print("ÑÐµÐ»Ñ Ð´Ð¾ÑÑигнÑÑа!")248                    power_found = True249                fire = False250            check_x_1 = start_Shell[0] <= x_location + barrier_width251            check_x_2 = start_Shell[0] >= x_location252            check_y_1 = start_Shell[1] <= display_height253            check_y_2 = start_Shell[1] >= display_height - random_Height254            if check_x_1 and check_x_2 and check_y_1 and check_y_2:255                hit_x = int((start_Shell[0]))256                hit_y = int(start_Shell[1])257                fire = False258    fire = True259    start_Shell = list(x_y)260    print("ÐгонÑ!", x_y)261    while fire:262        for event in pygame.event.get():263            if event.type == pygame.QUIT:264                pygame.quit()265                quit()266        pygame.draw.circle(gameDisplay, red, (start_Shell[0], start_Shell[1]), 5)267        start_Shell[0] += (12 - turPos) * 2268        shot_power = random.randrange(int(flowPower * 0.90), int(flowPower * 1.10))269        start_Shell[1] += int(270            (((start_Shell[0] - x_y[0]) * 0.015 / (shot_power / 50)) ** 2) - (turPos + turPos / (12 - turPos)))271        if start_Shell[1] > display_height - ground_height:272            print("поÑледние пÑоибиÑе:", start_Shell[0], start_Shell[1])273            hit_x = int((start_Shell[0] * display_height - ground_height) / start_Shell[1])274            hit_y = int(display_height - ground_height)275            print("УÑон:", hit_x, hit_y)276            if ptank_x + 10 > hit_x > ptank_x - 10:277                print("ÐÑиÑиÑеÑкий ÑÑон!")278                damage = 25279            elif ptank_x + 15 > hit_x > ptank_x - 15:280                print("СеÑÑезнÑй ÑÑон!")281                damage = 18282            elif ptank_x + 25 > hit_x > ptank_x - 25:283                print("СÑедний ÑÑон")284                damage = 10285            elif ptank_x + 35 > hit_x > ptank_x - 35:286                print("Ðегкий ÑÑон")287                damage = 5288            explosion(hit_x, hit_y)289            fire = False290        check_x_1 = start_Shell[0] <= x_location + barrier_width291        check_x_2 = start_Shell[0] >= x_location292        check_y_1 = start_Shell[1] <= display_height293        check_y_2 = start_Shell[1] >= display_height - random_Height294        if check_x_1 and check_x_2 and check_y_1 and check_y_2:295            print("ÐоÑледние пÑобиÑие:", start_Shell[0], start_Shell[1])296            hit_x = int((start_Shell[0]))297            hit_y = int(start_Shell[1])298            print("УÑон:", hit_x, hit_y)299            explosion(hit_x, hit_y)300            fire = False301        pygame.display.update()302        clock.tick(60)303    return damage304def power(level):305    text = smallfont.render("ÐоÑноÑÑÑ: " + str(level) + "%", True, wheat)306    gameDisplay.blit(text, [display_width / 2, 0])307def game_intro():308    intro = True309    while intro:310        for event in pygame.event.get():311            if event.type == pygame.QUIT:312                pygame.quit()313                quit()314            if event.type == pygame.KEYDOWN:315                if event.key == pygame.K_c:316                    intro = False317                elif event.key == pygame.K_q:318                    pygame.quit()319                    quit()320        gameDisplay.fill(black)321        message_to_screen("ÐобÑо пожаловаÑÑ Ð² Ñанки!", white, -120, size="large")322        button("ÐгÑаÑÑ", 150, 500, 100, 50, wheat, light_green, action="play",size="vsmall")323        button("УпÑавление", 350, 500, 100, 50, wheat, light_yellow, action="controls",size="vsmall")324        button("ÐÑÑ
од", 550, 500, 100, 50, wheat, light_red, action="quit",size="vsmall")325        pygame.display.update()326        clock.tick(15)327def game_over():328    game_over = True329    while game_over:330        for event in pygame.event.get():331            if event.type == pygame.QUIT:332                pygame.quit()333                quit()334        gameDisplay.fill(black)335        message_to_screen("ÐÑ Ð¿ÑоигÑали", white, -120, size="large")336        message_to_screen("Ð¢Ñ Ð¿Ð°Ð» ÑеÑÑÑÑ Ñ
ÑабÑÑÑ
", wheat, -30)337        button("ÐгÑаÑÑ Ñнова", 150, 600, 150, 50, wheat, light_green, action="play")338        button("УпÑавление", 350, 600, 100, 50, wheat, light_yellow, action="controls")339        button("ÐÑÑ
од", 550, 600, 100, 50, wheat, light_red, action="quit")340        pygame.display.update()341        clock.tick(15)342def you_win():343    win = True344    while win:345        for event in pygame.event.get():346            if event.type == pygame.QUIT:347                pygame.quit()348                quit()349        gameDisplay.fill(black)350        message_to_screen("Ð¢Ñ Ð¿Ð¾Ð±ÐµÐ´Ð¸Ð»!", white, -100, size="large")351        message_to_screen("ÐÑо бÑло невеÑоÑÑно!", wheat, -30)352        button("игÑаÑÑ Ñнова", 150, 600, 150, 50, wheat, light_green, action="play")353        button("ÑпÑавление", 350, 600, 100, 50, wheat, light_yellow, action="controls")354        button("вÑÑ
од", 550, 600, 100, 50, wheat, light_red, action="quit")355        pygame.display.update()356        clock.tick(15)357def health_bars(player_health, rival_health):358    if player_health > 75:359        player_health_color = green360    elif player_health > 50:361        player_health_color = yellow362    else:363        player_health_color = red364    if rival_health > 75:365        rival_health_color = green366    elif rival_health > 50:367        rival_health_color = yellow368    else:369        rival_health_color = red370    pygame.draw.rect(gameDisplay, player_health_color, (680, 25, player_health, 25))371    pygame.draw.rect(gameDisplay, rival_health_color, (20, 25, rival_health, 25))372def gameLoop():373    gameExit = False374    gameOver = False375    FPS = 30376    player_health = 100377    rival_health = 100378    barrier_width = 50379    main_Tank_X = display_width * 0.9380    mainTankY = display_height * 0.9381    tank_Move = 0382    flowTurPos = 0383    change_tur = 0384    rival_Tank_X = display_width * 0.1385    rival_Tank_Y = display_height * 0.9386    fire_power = 50387    power_change = 0388    x_location = (display_width / 2) + random.randint(-0.1 * display_width, 0.1 * display_width)389    random_Height = random.randrange(display_height * 0.1, display_height * 0.6)390    while not gameExit:391        if gameOver == True:392            message_to_screen("ÐгÑа оконÑена!", red, -50, size="large")393            message_to_screen("ÐажмиÑе С, ÑÑÐ¾Ð±Ñ Ð¸Ð³ÑаÑÑ Ñнова или Q Ð´Ð»Ñ Ð²ÑÑ
ода из игÑÑ", black, 50)394            pygame.display.update()395            while gameOver == True:396                for event in pygame.event.get():397                    if event.type == pygame.QUIT:398                        gameExit = True399                        gameOver = False400                    if event.type == pygame.KEYDOWN:401                        if event.key == pygame.K_c:402                            gameLoop()403                        elif event.key == pygame.K_q:404                            gameExit = True405                            gameOver = False406        for event in pygame.event.get():407            if event.type == pygame.QUIT:408                gameExit = True409            if event.type == pygame.KEYDOWN:410                if event.key == pygame.K_LEFT:411                    tank_Move = -5412                elif event.key == pygame.K_RIGHT:413                    tank_Move = 5414                elif event.key == pygame.K_UP:415                    change_tur = 1416                elif event.key == pygame.K_DOWN:417                    change_tur = -1418                elif event.key == pygame.K_p:419                    pause()420                elif event.key == pygame.K_SPACE:421                    damage = fireShell(shot, main_Tank_X, mainTankY, flowTurPos, fire_power, x_location, barrier_width,422                                       random_Height, rival_Tank_X, rival_Tank_Y)423                    rival_health -= damage424                    possibleMovement = ['f', 'r']425                    moveIndex = random.randrange(0, 2)426                    for x in range(random.randrange(0, 10)):427                        if display_width * 0.3 > rival_Tank_X > display_width * 0.03:428                            if possibleMovement[moveIndex] == "f":429                                rival_Tank_X += 5430                            elif possibleMovement[moveIndex] == "r":431                                rival_Tank_X -= 5432                            gameDisplay.fill(black)433                            health_bars(player_health, rival_health)434                            shot = tank(main_Tank_X, mainTankY, flowTurPos)435                            rival_shot = rival_tank(rival_Tank_X, rival_Tank_Y, 8)436                            fire_power += power_change437                            power(fire_power)438                            barrier(x_location, random_Height, barrier_width)439                            gameDisplay.fill(green,440                                             rect=[0, display_height - ground_height, display_width, ground_height])441                            pygame.display.update()442                            clock.tick(FPS)443                    damage = e_fireShell(rival_shot, rival_Tank_X, rival_Tank_Y, 8, 50, x_location, barrier_width,444                                         random_Height, main_Tank_X, mainTankY)445                    player_health -= damage446                elif event.key == pygame.K_a:447                    power_change = -1448                elif event.key == pygame.K_d:449                    power_change = 1450            elif event.type == pygame.KEYUP:451                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:452                    tank_Move = 0453                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:454                    change_tur = 0455                if event.key == pygame.K_a or event.key == pygame.K_d:456                    power_change = 0457        main_Tank_X += tank_Move458        flowTurPos += change_tur459        if flowTurPos > 8:460            flowTurPos = 8461        elif flowTurPos < 0:462            flowTurPos = 0463        if main_Tank_X - (tankWidth / 2) < x_location + barrier_width:464            main_Tank_X += 5465        gameDisplay.fill(black)466        health_bars(player_health, rival_health)467        shot = tank(main_Tank_X, mainTankY, flowTurPos)468        rival_shot = rival_tank(rival_Tank_X, rival_Tank_Y, 8)469        fire_power += power_change470        if fire_power > 100:471            fire_power = 100472        elif fire_power < 1:473            fire_power = 1474        power(fire_power)475        barrier(x_location, random_Height, barrier_width)476        gameDisplay.fill(green, rect=[0, display_height - ground_height, display_width, ground_height])477        pygame.display.update()478        if player_health < 1:479            game_over()480        elif rival_health < 1:481            you_win()482        clock.tick(FPS)483    pygame.quit()484    quit()485game_intro()...server.py
Source:server.py  
...53            print("COMMANDS:\n" + "show all ---------------- display all countries and clients connected to server\n" + "choice ID# ------------- select the number in front of country\n"54                  + "client ID#--------------------- returns the json for the client that selected the country\n" + "quit ---------------------- exit current client when called in send target function\n" + "exit  ------------------------------- exits the program\n")55        except:56            print("Error accepting connections")57def start_shell():58    cmd = str(input('shell> '))59    if cmd.lower() == 'exit':60        print("ending program")61        raise SystemExit62    while cmd.lower != 'quit':63        if cmd.lower() == 'show all':64            showCountries()65            create_client_list()66            list_connections()67            cmd = str(input('shell> '))68        elif 'choice' in cmd.lower():69            ID = get_country(cmd)70            print(b.getJson, ID)71        elif 'client' in cmd.lower():72            conn = get_target(cmd)73            if conn is None:74                send_target_commands(conn)75        else:76            if cmd.lower() == 'exit':77                raise SystemExit78            send_target_commands(cmd)79            print("Command not recognized")80        receive_client_input(conn)81def showCountries():82    countries = []83    for i in range(len(b.individual_country_list)):84        id_country = str(i) + " " + str(b.individual_country_list[i])85        print(id_country)86def create_client_list():87    client_string = ""88    for c, conn in enumerate(all_connections):89        try:90            temp = str(c) + "   " + str(all_address[c][0]) + "   " + str(all_address[c][1]) + "\n"91            client_string = client_string + temp92        except:93            print("Clients could not be retrieved....")94    print("-------------Clients--------------\n" + client_string)95def list_connections():96    for i, conn in enumerate(all_connections):97        try:98            conn.send(str.encode(' '))99            data = conn.recv(1024)100            print(data)101        except:102            del all_connections[i]103            del all_address[i]104            continue105    start_shell()106def get_country(cmd):107    try:108        countryID = cmd.replace('choice ', '')109        countryID = int(countryID)110        print("You have selected", b.individual_country_list[countryID])111        print(b.getJson(countryID))112    except:113        print("invalid countryID")114def get_target(cmd):115    try:116        shellID = cmd.replace('client ', '')117        shellID = int(shellID)118        conn = all_connections[shellID]119        print("Now connected to: " + str(all_address[shellID]))120        #print(str(all_address[shellID][0]) + ">", end="")121        receive_client_input(conn)122        return conn123    except:124        print("Selection not valid")125        return None126def send_target_commands(conn):127    while True:128        try:129            print("Press 'Enter' key if not connected to client to retype shell command or 'quit' to exit current client")130            cmd = str(input('shell>>'))131            if cmd.lower() == 'quit':132                goodbye = "goodbye"133                print(goodbye)134                conn.send(goodbye.encode())135                start_shell()136            if len(str.encode(cmd)) > 0:137                conn.send(cmd.encode())138                client_response = str(conn.recv(1024), "utf-8")139                print(client_response, '\n', end="")140                if client_response == 'exit':141                    start_shell()142                else:143                    send_target_commands(conn)144            else:145                start_shell()146        except:147            print("Error sending commands")148            start_shell()149            break150def receive_client_input(conn):151    client_selection = conn.recv(1024)152    c_id = client_selection.decode()153    print("this is c id", c_id, int(c_id))154    country_json = b.getJson(int(client_selection))155    print(country_json)156    conn.send(country_json.encode())157    start_shell()158def create_threads():159    for _ in range(thread_count):160        t = threading.Thread(target=get_queue)161        t.daemon = True162        t.start()163def get_queue():164    while True:165        x = queue.get()166        if x == 1:167            create_socket()168            bind_socket()169            accepting_connections()170        if x == 2:171            start_shell()172        queue.task_done()173def create_queue():174    for x in connection_jobs:175        queue.put(x)176    queue.join()177create_threads()...floodlight.py
Source:floodlight.py  
1"""2manage floodlight instance3"""4import logging5import subprocess6import shutil7import os8import time9import signal10class FloodlightController ( object ):11    "manage floodlight controller"12    def __init__ (self, auto_start = False, start_shell=None):13        self.start_shell = start_shell14        self.auto_start = auto_start15        self.has_started = False16        self.process = None17        if self.auto_start:18            if start_shell == None:19                raise RuntimeError('we want the controller starting shell path if the controller is automatically delegated.')20            else:21                self.start_floodlight( )22    def start_floodlight ( self ):23        "start the floodlight"24        if self.has_started:25            return26        self.has_started = True27        cmds = self.start_shell.split()28        cwd = self.get_cwd_from_shell_path( )29        with open(os.devnull, 'w')  as DEVNULL:30            try:31                self.process = subprocess.Popen(cmds, cwd=cwd, stdout=DEVNULL, stderr=DEVNULL)32            except subprocess.CalledProcessError:33                logging.error('cannot start floodlight controller, exit')34                raise RuntimeError('cannot start floodlight controller')35        logging.info('sleep 5 seconds to wait for floodlight start')36        time.sleep(5)37    def get_cwd_from_shell_path( self ):38        "get the cwd from the shell scripts"39        idx = self.start_shell.rfind('/')40        return self.start_shell[:idx]41    def get_floodlight_pid( self ):42        "get the pid of floodlight"43        cmds = 'pgrep -f java.*floodlight'.split()44        p = subprocess.Popen(cmds, stdout=subprocess.PIPE)45        out, err = p.communicate()46        pid = None47        for line in out.splitlines():48            pid = int(line)49        return pid50    51    def check_status( self ):52        "is the controller is running?"53        pid = self.get_floodlight_pid( )54        return True if pid != None else False55        56    def stop_floodlight( self ):57        "just stop floodlight"58        pid = self.get_floodlight_pid()59        if pid != None:60            logging.info('killing floodlight process {}'.format(pid))61            os.kill(pid, signal.SIGTERM)62        else:63            logging.error('cannot find floodlight process')64        self.process = None65        self.has_started = None66    def get_log_path( self ):67        return '/tmp/floodlight.log'68    def get_config_path( self ):69        if self.start_shell:70            idx = self.start_shell.rfind('/')71            parent_path = self.start_shell[:idx]72            return parent_path + '/src/main/resources/floodlightdefault.properties'73        else:74            return None75    def clean_floodlight( self ):76        "stop process and clean logs"77        if self.has_started:78            self.stop_floodlight()79        # remove logs80        try:81            os.remove( self.get_log_path() )82        except OSError:83            pass84        85    def retrieve_floodlight_log( self, target_path ):86        "copy logs to another file"87        if self.auto_start:88            shutil.copy(self.get_log_path(), target_path)89    def retrieve_floodlight_config( self, target_path ):90        "copy configurations"91        shutil.copy(self.get_config_path(), target_path)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
