Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 连接测试和循环,以防断开连接,防止脚本结束_Python_Python 3.x_Python Requests - Fatal编程技术网

Python 连接测试和循环,以防断开连接,防止脚本结束

Python 连接测试和循环,以防断开连接,防止脚本结束,python,python-3.x,python-requests,Python,Python 3.x,Python Requests,我有一个脚本,它在raspbery Zero上连续运行,以捕获温度并将其发送给grafana。问题是,当grafana服务器停止进行备份或其他操作时,该脚本出错,无法自动恢复,因此我正在寻找一种方法来创建一个可用于发送数据的连接测试循环,如果grafana服务器停止服务,则连续脚本会一直工作,直到grafana服务器启动并运行,从而恢复将温度数据发送到grafana服务器 因为当前的脚本在消息中出现了错误 requests.exceptions.ConnectionError:HTTPConne

我有一个脚本,它在raspbery Zero上连续运行,以捕获温度并将其发送给grafana。问题是,当grafana服务器停止进行备份或其他操作时,该脚本出错,无法自动恢复,因此我正在寻找一种方法来创建一个可用于发送数据的连接测试循环,如果grafana服务器停止服务,则连续脚本会一直工作,直到grafana服务器启动并运行,从而恢复将温度数据发送到grafana服务器

因为当前的脚本在消息中出现了错误
requests.exceptions.ConnectionError:HTTPConnectionPool

使用脚本
python templogger.py-db=influx\u db\u temperature-sn=temperature-rn=RUN

我的剧本:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import glob
import argparse
import time
import datetime
import sys
from influxdb import InfluxDBClient

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# add more sensor variables here based on your setup

# For multiple sensor
# temp=['sensor code','tttttttttt','ddddddddddd','ssssssssss']
temp=['0120215dbea2','0120327e05bf']
base_dir = '/sys/bus/w1/devices/'

# Ext = 28-0120215dbea2
# Int = 28-0120327e05bf

device_folders = glob.glob(base_dir + '28*')

snum=2 #Number of connected temperature sensors

# Set required InfluxDB parameters.
# (this could be added to the program args instead of beeing hard coded...)
host = "NasGrafana.lan.prive" #Could also use local ip address like "192.168.1.136"
port = 8086
user = "temperature"
password = "12345678"
 
# Sample period (s).
# How frequently we will write sensor data from the temperature sensors to the database.
sampling_period = 120

def read_temp_raw(device_file): 
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp(device_file): # checks the temp recieved for errors
    lines = read_temp_raw(device_file)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw(device_file)

    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        # set proper decimal place for C
        temp = float(temp_string) / 1000.0
        # Round temp to 2 decimal points
        temp = round(temp, 1)
    # value of temp might be unknown here if equals_pos == -1
    return temp

def get_args():
    '''This function parses and returns arguments passed in'''
    # Assign description to the help doc
    parser = argparse.ArgumentParser(description='Program writes measurements data from the connected DS18B20 to specified influx db.')
    # Add arguments
    parser.add_argument(
        '-db','--database', type=str, help='Database name', required=True)
    parser.add_argument(
        '-sn','--session', type=str, help='Session', required=True)
    now = datetime.datetime.now()
    parser.add_argument(
        '-rn','--run', type=str, help='Run number', required=False,default=now.strftime("%Y%m%d%H%M"))
    
    # Array of all arguments passed to script
    args=parser.parse_args()
    # Assign args to variables
    dbname=args.database
    runNo=args.run
    session=args.session
    return dbname, session,runNo
    
def get_data_points():
    # Get the three measurement values from the DS18B20 sensors
    for sensors in range (snum): # change number of sensors based on your setup
        device_file=device_folders[sensors]+ '/w1_slave'
        temp[sensors] = read_temp(device_file)
        print (device_file,sensors,temp[sensors])
    # Get a local timestamp
    timestamp=datetime.datetime.utcnow().isoformat()
    NumDevice=os.path.basename(os.path.dirname(device_file))
    
    # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)
    datapoints = [
        {
            "measurement": session,
            # "tags": {"runNum": NumDevice,},
            "tags": {"runNum": runNo,},
            "time": timestamp,
            #"fields": {"temperature 1":temp[0],"temperature 2":temp[1],"temperature 3":temp[2],"temperature 4":temp[3]}
            "fields": {"temperature 1":temp[0],"temperature 2":temp[1]}
        }
        ]
    return datapoints

# Match return values from get_arguments()
# and assign to their respective variables
dbname, session, runNo =get_args()   
print ("Session: ", session)
print ("Run No: ", runNo)
print ("DB name: ", dbname)

# Initialize the Influxdb client
client = InfluxDBClient(host, port, user, password, dbname)
        
try:
     while True:
        # Write datapoints to InfluxDB
        datapoints=get_data_points()
        bResult=client.write_points(datapoints)
        print("Write points {0} Bresult:{1}".format(datapoints,bResult))
            
        # Wait for next sample
        time.sleep(sampling_period)
        
        # Run until keyboard ctrl-c
except KeyboardInterrupt:
    print ("Program stopped by keyboard interrupt [CTRL_C] by user. ")

感谢@AbhinavMathur迫使我继续添加一个try,只是因为最后我没有在脚本中正确定位

这是允许脚本不会因连接错误而崩溃的modif

#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import glob
import argparse
import time
import datetime
import sys
from influxdb import InfluxDBClient

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

# add more sensor variables here based on your setup

# For multiple sensor
# temp=['sensor code','tttttttttt','ddddddddddd','ssssssssss']
temp=['0120215dbea2','0120327e05bf']
base_dir = '/sys/bus/w1/devices/'

# Ext = 28-0120215dbea2
# Int = 28-0120327e05bf

device_folders = glob.glob(base_dir + '28*')

snum=2 #Number of connected temperature sensors

# Set required InfluxDB parameters.
# (this could be added to the program args instead of beeing hard coded...)
host = "NasGrafana.lan.prive" #Could also use local ip address like "192.168.1.136"
port = 8086
user = "temperature"
password = "12345678"
 
# Sample period (s).
# How frequently we will write sensor data from the temperature sensors to the database.
sampling_period = 120

def read_temp_raw(device_file): 
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp(device_file): # checks the temp recieved for errors
    lines = read_temp_raw(device_file)
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw(device_file)

    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        # set proper decimal place for C
        temp = float(temp_string) / 1000.0
        # Round temp to 2 decimal points
        temp = round(temp, 1)
    # value of temp might be unknown here if equals_pos == -1
    return temp

def get_args():
    '''This function parses and returns arguments passed in'''
    # Assign description to the help doc
    parser = argparse.ArgumentParser(description='Program writes measurements data from the connected DS18B20 to specified influx db.')
    # Add arguments
    parser.add_argument(
        '-db','--database', type=str, help='Database name', required=True)
    parser.add_argument(
        '-sn','--session', type=str, help='Session', required=True)
    now = datetime.datetime.now()
    parser.add_argument(
        '-rn','--run', type=str, help='Run number', required=False,default=now.strftime("%Y%m%d%H%M"))
    
    # Array of all arguments passed to script
    args=parser.parse_args()
    # Assign args to variables
    dbname=args.database
    runNo=args.run
    session=args.session
    return dbname, session,runNo
    
def get_data_points():
    # Get the three measurement values from the DS18B20 sensors
    for sensors in range (snum): # change number of sensors based on your setup
        device_file=device_folders[sensors]+ '/w1_slave'
        temp[sensors] = read_temp(device_file)
        print (device_file,sensors,temp[sensors])
    # Get a local timestamp
    timestamp=datetime.datetime.utcnow().isoformat()
    NumDevice=os.path.basename(os.path.dirname(device_file))
    
    # Create Influxdb datapoints (using lineprotocol as of Influxdb >1.1)
    datapoints = [
        {
            "measurement": session,
            # "tags": {"runNum": NumDevice,},
            "tags": {"runNum": runNo,},
            "time": timestamp,
            #"fields": {"temperature 1":temp[0],"temperature 2":temp[1],"temperature 3":temp[2],"temperature 4":temp[3]}
            "fields": {"temperature 1":temp[0],"temperature 2":temp[1]}
        }
        ]
    return datapoints

# Match return values from get_arguments()
# and assign to their respective variables
dbname, session, runNo =get_args()   
print ("Session: ", session)
print ("Run No: ", runNo)
print ("DB name: ", dbname)

# Initialize the Influxdb client
client = InfluxDBClient(host, port, user, password, dbname)
        
try:
     while True:
        # Write datapoints to InfluxDB
        datapoints=get_data_points()
        try:
            bResult=client.write_points(datapoints)
            print("Write points {0} Bresult:{1}".format(datapoints,bResult))
        except:
            print("Error lan connection")
            #time.sleep(30)
            #continue
            
        # Wait for next sample
        time.sleep(sampling_period)
        
        # Run until keyboard ctrl-c
except KeyboardInterrupt:
    print ("Program stopped by keyboard interrupt [CTRL_C] by user. ")


您是否尝试过使用
try except
来阻止退出?@AbhinavMathur我测试了
except:continue
,但我得到了以下错误:
>语法错误:“continue”在循环中不正确