Как отфильтровать часть вывода функции - PullRequest
0 голосов
/ 25 декабря 2018

Мне нужно распечатать на экране ips интерфейсов моего компьютера, библиотека, которую я использую, позволяет мне печатать только адреса IPv6 и IPv4, я только хочу печатать IPv4.

Этот код будет работать на Linux-сервере "OpenMediaVault" (на нем нет ifconfig, но ifaddr или что-то в этом роде), я полный нуб с python, а не опытный пользователь linux.

import time
import pygame
import sys
import ifaddr

display_width = 480
display_height = 320
white = (255, 255, 255)
black = (0, 0, 0)
fontSize = 20
adapters = ifaddr.get_adapters()

pygame.init()
screen = pygame.display.set_mode((display_width,display_height),pygame.FULLSCREEN)

def text_objects(text, font):
    textSurface = font.render(text, True, white)
    return textSurface, textSurface.get_rect()


while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                pygame.quit()

    for adapter in adapters:
        #print (adapter.nice_name + ":")

        for ip in adapter.ips:
            #print (ip.ip)

            IP = ip.ip

            largeText = pygame.font.Font(pygame.font.get_default_font(),fontSize)
            TextSurf,TextRect=text_objects((adapter.nice_name + ":"),largeText)
            TextRect.center = ((display_width/2),(1*(display_height/4)))
            screen.blit(TextSurf, TextRect)

            largeText = pygame.font.Font(pygame.font.get_default_font(),fontSize)
            TextSurf,TextRect=text_objects((IP), largeText)
            TextRect.center = ((display_width/2),(3*(display_height/4)))
            screen.blit(TextSurf, TextRect)

            time.sleep(1)

            screen.fill((0,0,0))
            pygame.display.flip()
            pygame.display.update()

Ошибка, которую я получаю, потому что я пытаюсь напечатать на экране с помощью pygames:

pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "d:\Desktop\***\file.py", line 45, in <module>    TextSurf, TextRect = text_objects((IP), largeText)
File "d:\Desktop\***\file.py", line 17, in text_objects    textSurface = font.render(text, True, white)
TypeError: text must be a unicode or bytes

Вывод, который я получу, если япечать только на консоль:

Realtek PCIe GbE Family Controller:
('fd3a:8044:257f::c85', 0, 0)
('fd3a:8044:257f:0:2947:5034:62b0:c9c8', 0, 0)
('fd3a:8044:257f:0:e536:c13a:a8ec:e003', 0, 0)
('fe80::e536:c13a:a8ec:e003', 0, 14)
169.254.224.3
Atheros AR9271 Wireless Network Adapter:
('fe80::9dd2:117c:d9ec:a07a', 0, 25)
192.168.43.118
Software Loopback Interface 1:
('::1', 0, 0)
127.0.0.1

Требуемый вывод (и ips, напечатанные на экране или, по крайней мере, в переменной char):

Realtek PCIe GbE Family Controller:
169.254.224.3
Atheros AR9271 Wireless Network Adapter:
192.168.43.118
Software Loopback Interface 1:
127.0.0.1

Заранее спасибо.

1 Ответ

0 голосов
/ 25 декабря 2018

Адрес IPv4 - это строка, адрес IPv6 - это кортеж.Так что просто проверьте, является ли ip строка, и пропустите ее.

for ip in adapter.ips:
    if not isinstance(ip.ip, str):
        continue

    #rest of loop body goes here
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...