Python中Tk和Ping的问题
我在用Tk的时候,遇到了一行代码无法正常运行的问题。
import os
while(1):
ping = os.popen('ping www.google.com -n 1')
result = ping.readlines()
msLine = result[-1].strip()
print msLine.split(' = ')[-1]
我想创建一个标签,然后用msLine.split来处理文本,但程序却卡住了。
2 个回答
0
使用Tk和popen()时可能会遇到其他问题。首先:
不要不停地去ping或者从google.com获取数据。
在代码的最上面加上“import time”,然后在while循环的底部加上“time.sleep(2)”。这样可以让程序每次循环之间停顿2秒。
其次:
你可能想用“ping www.google.com -c 1”,而不是“-n 1”。“-c 1”表示只发送一次ping请求,而“-n 1”则是ping一个特殊的地址0.0.0.1。
0
你的示例代码没有包含任何图形用户界面(GUI)的代码。没有看到这些代码,很难猜测为什么你的界面会卡住。不过,你的代码本身就有很多问题,即使有GUI的代码在你的帖子里,也可能帮不上忙。
你有没有可能忘记在你的根部件上调用mainloop()方法?如果没有调用这个方法,那就能解释为什么会卡住。如果你已经在调用mainloop(),那么就没有必要再用while(1)了,因为主事件循环本身就是一个无限循环。你为什么要在一个循环里调用ping呢?
你有一个具体的问题,就是你调用ping的方式不对。首先,选项“-n 1”应该放在主机名参数之前(也就是说,应该是'ping -n 1 www.google.com',而不是'ping www.google.com -n 1')。另外,-n这个选项也不对。我觉得你应该用“-c 1”。
这里有一个可以定期ping并更新标签的工作示例:
import os
from Tkinter import *
class App:
def __init__(self):
self.root = Tk()
self.create_ui()
self.url = "www.google.com"
self.do_ping = False
self.root.mainloop()
def create_ui(self):
self.label = Label(self.root, width=32, text="Ping!")
self.button = Button(text="Start", width=5, command=self.toggle)
self.button.pack(side="top")
self.label.pack(side="top", fill="both", expand=True)
def toggle(self):
if self.do_ping:
self.do_ping = False
self.button.configure(text="Start")
else:
self.do_ping = True
self.button.configure(text="Stop")
self.ping()
def ping(self):
if not self.do_ping:
return
ping = os.popen('ping -c 1 %s' % self.url)
result = ping.readlines()
msLine = result[-1].strip()
data = msLine.split(' = ')[-1]
self.label.configure(text=data)
# re-schedule to run in another half-second
if self.do_ping:
self.root.after(500, self.ping)
app=App()