我有一個 Python 腳本,它通過 ping 每 30 秒確定一次互聯網速度,以查看用戶是否可以通過互聯網接聽電話,ping 通常不足以了解這一點,因此我想要更多資訊,例如下載速度和網路上傳速度等等。
這如何在 Python 中發生而不會對 Internet 產生重大影響,從而不會導致 Internet 速度變慢
`
def check_ping(host):
"""
Returns formated min / avg / max / mdev if there is a vaild host
Return None if host is not vaild
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower() == 'windows' else '-c'
# Building the command. Ex: "ping -c 1 $host"
command = ['ping', param, '3', host]
# ask system to make ping and return output
ping = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, error = ping.communicate()
matcher = re.compile(
"(\d .\d )/(\d .\d )/(\d .\d )/(\d .\d )")
# rtt min/avg/max/mdev =
ping_list = r"Minimum = (\d )ms, Maximum = (\d )ms, Average = (\d )ms"
try:
if(not error):
if(platform.system().lower() == 'windows'):
response = re.findall(ping_list, out.decode())[0]
return response
else:
response = matcher.search(out.decode()).group().split('/')
return response
except Exception as e:
logging.error(e)
return None
`
uj5u.com熱心網友回復:
pyspeedtest為您提供您想要的功能。
這是官方頁面的一個片段。
>>> import pyspeedtest
>>> st = pyspeedtest.SpeedTest()
>>> st.ping()
9.306252002716064
>>> st.download()
42762976.92544772
>>> st.upload()
19425388.307319913
還有speedtest-cli但這不是我個人嘗試過的。
如果您正在尋找更多東西,那么您必須基于以下內容提出自己的實作 sockets
編輯: 這是基于使用請求的實作
#!/usr/bin/env python3
import requests, os, sys, time
def test_connection(type):
nullFile = os.devnull
with open(nullFile, "wb") as f:
start = time.clock()
if type == 'download':
r = requests.get('https://httpbin.org/get', stream=True)
elif type == 'upload':
r = requests.post('https://httpbin.org/post', data={'key': 'value'})
else:
print("unknown operation")
raise
total_length = r.headers.get('content-length')
dl = 0
for chunk in r.iter_content(1024):
dl = len(chunk)
f.write(chunk)
done = int(30 * dl / int(total_length))
sys.stdout.write("\r%s: [%s%s] %s Mbps" % (type, '=' * done, ' ' * (30-done), dl//(time.clock() - start) / 100000))
print('')
# Example usage
test_connection("download")
test_connection("upload")
輸出:
download: [==============================] 0.13171 Mbps
upload: [==============================] 0.20217 Mbps
您可能可以修改此函式以接受 url/IP 作為引數。此外,您可以requests在官方頁面上找到有關模塊的更多詳細資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/377924.html
