[英]Why am i getting a host not found error when running my python ping script?
我不久前制作了这个脚本,如果我没记错的话它可以工作,但现在我得到一个找不到主机错误。 任何帮助表示赞赏。
from tkinter import *
from tkinter import ttk
import socket
import sqlite3
import subprocess
BASE = Tk()
BASE.geometry("400x400")
def PING_CLIENT():
HOST = PING_ENTRY
command = "ping {} 30 -t".format(HOST)
subprocess.run(command)
PING = ttk.Button(BASE, text="Ping IP", command=PING_CLIENT)
PING.place(x=35, y=100, height=30, width=150)
PING_ENTRY = ttk.Entry(BASE)
PING_ENTRY.place(x=200, y=100, height=30, width=150)
BASE.mainloop()
您需要获取 Entry 小部件的值。 为此,请在小部件上调用get()
方法。 您可以在此处阅读有关 Tkinter 条目小部件的更多信息。
例子:
HOST = PING_ENTRY.get()
另外,我不确定您命令中的“30”应该做什么。 如果您打算 ping 30 次,则需要预先添加-n
开关(在 Windows 上)或-c
开关(在大多数 Linux 发行版上)。 例如,在 Windows 上:
command = "ping {} -n 30 -t".format(HOST)
@AndroidNoobie 的回答很好。 我添加这个以防万一您希望执行是异步的,您可以使用subprocess.Popen
而不是subprocess.run
。
UI 冻结,直到run
执行完成。 如果您不希望这种情况发生,我建议您使用subprocess.Popen
def PING_CLIENT():
HOST = PING_ENTRY.get()
command = "ping {} -n 30 -t".format(HOST)
#subprocess.run(command, shell=True)
subprocess.Popen(command, shell=True)
从另一个 SO 答案:主要区别在于subprocess.run
执行一个命令并等待它完成,而使用subprocess.Popen
您可以在进程完成时继续做你的事情,然后重复调用 subprocess.communicate 自己通过和接收数据到您的流程。
编辑:添加代码以在 30 次试验后停止 ping。
要使您的代码在特定数量的数据包后停止,请使用以下代码。
Windows:
command = "ping -n 30 {}".format(HOST)
pro = subprocess.Popen(command, shell=True,stdout=subprocess.PIPE)
print(pro.communicate()[0]) # prints the stdout
Ubuntu:
command = "ping -c 30 {}".format(HOST)
pro = subprocess.Popen(command, shell=True,stdout=subprocess.PIPE)
print(pro.communicate()[0]) # prints the stdout
-t 基本上在 windows 中无限期地 ping。这就是你无法阻止它的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.