[英]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.