为什么在运行python ping脚本时出现主机未找到错误?

时间:2020-06-28 14:21:05

标签: python ping

我前一阵子做了这个脚本,如果我没记错的话,它可以正常工作,但是现在我得到了一个找不到主机错误。任何帮助表示赞赏。

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()

2 个答案:

答案 0 :(得分:3)

您需要获取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)

答案 1 :(得分:1)

@AndroidNoobie的答案很好用。如果您希望执行异步,可以添加subprocess.run而不是run

UI冻结,直到完成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)

subprocess.run

从另一个SO answer: 主要区别在于subprocess.Popen执行命令并等待其完成,而使用 command = "ping -n 30 {}".format(HOST) pro = subprocess.Popen(command, shell=True,stdout=subprocess.PIPE) print(pro.communicate()[0]) # prints the stdout 则可以在过程完成时继续执行您的工作,然后重复调用subprocess。进行通信以传递和接收数据传输到您的流程。

编辑:添加代码以在30次试用后停止ping操作。

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

Windows:

    command = "ping -c 30 {}".format(HOST)
    pro = subprocess.Popen(command, shell=True,stdout=subprocess.PIPE)
    print(pro.communicate()[0]) # prints the stdout

Ubuntu:

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@$!%*?&])([a-zA-Z0-9@$!%*?&]{8,})$

-t基本上在Windows中无限期ping,这就是为什么您无法停止它。