为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3146593 2023-02-07 15:56:02
我不久前制作了这个脚本,如果我没记错的话它可以正常工作,但现在我遇到了找不到主机的错误。任何帮助表示赞赏。from tkinter import *from tkinter import ttkimport socketimport sqlite3import subprocessBASE = 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 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

您需要获取 Entry 小部件的值。为此,请调用get()小部件上的方法。您可以在此处阅读有关Tkinter Entry Widget的更多信息。

例子:

HOST = PING_ENTRY.get()

另外,我不确定您命令中的“30”应该做什么。如果您打算让它 ping 30 次,则需要-n预先添加开关(在 Windows 上)或-c开关(在大多数 Linux 发行版上)。例如,在 Windows 上:

command = "ping {} -n 30 -t".format(HOST)


查看完整回答
反对 回复 2023-02-07
?
慕斯王

TA贡献1864条经验 获得超2个赞

我添加这个只是为了以防万一您希望异步执行,您可以使用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 次试验后停止。


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


视窗:


    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。这就是为什么你无法阻止它。


查看完整回答
反对 回复 2023-02-07
  • 2 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信