ValueError:无法将字符串转换为float:变量中为空字符串

时间:2018-08-07 09:33:17

标签: python python-2.7

我有一个值错误,我该如何解决它,当我的脚本崩溃变量获取空字符串时,我尝试编写用于ping的脚本,并从服务器获取响应时间,如果时间超过100我会打印错误,如果很低100我打印良好,但是在某个地方我从ping输出中得到空字符串,并且我不知道如何解决此问题,如果您知道如何改进我的代码,我很高兴看到您的评论,我只是在python中训练。预先谢谢你。

import subprocess
import time
import os
import re


def main():
    host_list = ['google.com', 'facebook.com', 'gmail.com', 'vk.com', '114.141.102.124', '192.168.255.129', '8.8.8.8']
    while True:
        for item in host_list:
            command = "ping " + item + " -c 1"
            ping = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
            ping_out = ping.communicate()[0]
            pattern_ping_time = r'(time=\d{0,4}.\d{0,2})'
            pattern_connection_lost = r'(100% packet loss)'
            time_r = re.findall(pattern_ping_time, ping_out)
            conn_lost = re.findall(pattern_connection_lost, ping_out)
            time_r_s = ''.join(time_r)
            time_r_s_form = time_r_s.strip('time=')
            print(time_r_s_form)
            time_r_s_form_float = float(time_r_s_form)
            print(time_r_s_form_float)
            if time_r_s_form_float > 100.0:
                print(item + "  " + '\x1b[0;30;41m' + "bad" + '\x1b[0m')
            elif time_r_s_form_float < 100.0:
                print(item + "  " + '\x1b[6;30;42m' + "good" + '\x1b[0m')
            elif conn_lost:
                print(item + "  " + '\x1b[0;30;41m' + "connection lost" + '\x1b[0m')
            else:
                print("no data")
        time.sleep(1)
        os.system('clear')


if __name__=="__main__":
    main()

输出:

47.2
47.2
google.com  good
39.5
39.5
facebook.com  good
45.5
45.5
gmail.com  good
72.3
72.3
vk.com  good

Traceback (most recent call last):
  File "script.py", line 63, in <module>
    main()
  File "script.py", line 22, in main
    time_r_s_form_float = float(time_r_s_form)
ValueError: could not convert string to float: 

0 个答案:

没有答案