为什么我在 运行 我的 python ping 脚本时收到主机未找到错误?

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 Entry Widget here.

的更多信息

示例:

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 来传递并将数据接收到您的进程。

编辑:添加代码使 ping 在 30 次试验后停止。

要使您的代码在特定数量的数据包后停止,请使用以下代码。

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.That 中无限期地 ping,这就是你无法阻止它的原因。