如何过滤函数输出的一部分

时间:2018-12-24 22:06:02

标签: python pygame

我需要在屏幕上打印我的计算机界面的ips, 我正在使用的库只允许我打印IPv6和IPv4地址, 我只希望打印IPv4。

此代码将在“ OpenMediaVault” Linux服务器上运行(它没有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

我想要的输出(以及打印在屏幕上或至少在char变量中的ip):

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 :(得分:0)

IPv4地址是字符串,IPv6地址是元组。因此,只需检查ip是否为字符串,然后跳过它即可。

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

    #rest of loop body goes here
相关问题