0

我有 60 个间隔,想每 1 分钟打印 6 个事件。但它每 1 分钟随机打印 11,12 和 13 个事件。为什么呢 ?是因为我的代码还是其他因素会导致这种情况?

我的代码是 -

import logging
import httplib
import simplejson as json
import socket
import time
import datetime
import urllib2
import sys
import xml.dom.minidom
from bs4 import BeautifulSoup as soup




SCHEME = """<scheme>
   <title>testingCurrentWeatherSG</title>
   <description>Get data from forecast.</description>
   <use_external_validation>true</use_external_validation>
   <streaming_mode>simple</streaming_mode>
   <endpoint>
       <args>
           <arg name="intervalone">
               <title>Intervalone</title>
               <description>How long to refresh this query?</description>
           </arg>
       </args>  
   </endpoint>
</scheme>
"""



def do_scheme():
    print SCHEME

## Utility functions
def fahrenheit(fahren):
    return (fahren-32) * 5.0/9.0

def get_percent(num):
    return num * 100.

## Responses
def get_response(conn, url):
    try:
        conn.request('GET', url)
        result = conn.getresponse()
        data = result.read()
        return json.loads(data)
    except socket.timeout:
        return None

## Printing
def print_forecast(name, di):
    # Print the forcast from 'di', for location 'name'
    # name is the name of the location, di is the api response
    psi_avg=20


    current = di['currently']
    for key, value in sorted(current.iteritems()):
        if key in ['cloudCover', 'icon', 'ozone', 'precipIntensity', # time
                   'precipProbability', 'precipType', 'pressure', 'summary',
                   'visibility', 'windBearing', 'windSpeed']:
            print '{0} : {1}'.format(key, value)

        elif key in ['temperature', 'dewPoint']:
            print '%s: %.2f' % (key, fahrenheit(value))
        elif key == 'humidity':
            print '%s: %.2f' % (key, get_percent(value))

    print 'psiAverage : ' + str(psi_avg)
    print 'latitude : ' + str(di['latitude'])
    print 'longitude : ' + str(di['longitude'])
    print 'location : ' + str(name)
    print

def weather_Connection(intervalone):
    host = 'api.forecast.io'
    conn = httplib.HTTPSConnection(host, timeout=60) # adjust timeout as desired

    try:
        urlnyp = '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.37871,103.848808'
        conn.request('GET', urlnyp)
        resultnyp = conn.getresponse()
        contentnyp = resultnyp.read()
    except socket.timeout:
        print 'socket timeout'
        return

    # the locations and urls for the api calls
    urls = {
        'Choa Chu Kang': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.394557,103.746396',
        'Kallang': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.311469,103.871399',
        'Jurong West': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.352008,103.698599',
        'Redhill': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.289732,103.81675',
        'Tampines': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.353092,103.945229',
        'Yishun': '/forecast/59ff8cb7661d231f2967c2663c0a3bdc/1.429463,103.84022',
    }

    responses = {}
    for i, (name, url) in enumerate(sorted(urls.iteritems())):
        response = get_response(conn, url)
        if not response:
            print 'socket timeout on url#%d: %s' % (i, url)
            return
        responses[name] = response

    conn.close()

    # print the forecast
    for name, data in responses.iteritems():
        print_forecast(name, data)


def get_config():
    #Read XML Configuration data passed from splunkd on stdin
    config = {}

    try:
        # read everything from stdin
        config_str = sys.stdin.read()

        # parse the config XML
        doc = xml.dom.minidom.parseString(config_str)
        root = doc.documentElement
        conf_node = root.getElementsByTagName("configuration")[0]
        if conf_node:
            logging.debug("XML: found configuration")
            stanza = conf_node.getElementsByTagName("stanza")[0]
            if stanza:
                stanza_name = stanza.getAttribute("name")
                if stanza_name:
                    logging.debug("XML: found stanza " + stanza_name)
                    config["name"] = stanza_name

                    params = stanza.getElementsByTagName("param")
                    for param in params:
                        param_name = param.getAttribute("name")
                        logging.debug("XML: found param '%s'" % param_name)
                        if param_name and param.firstChild and \
                           param.firstChild.nodeType == param.firstChild.TEXT_NODE:
                            data = param.firstChild.data
                            config[param_name] = data
                            logging.debug("XML: '%s' -> '%s'" % (param_name, data))


        if not config:
            raise Exception, "Invalid configuration received from Splunk."

    except Exception, e:
        raise Exception, "Error getting Splunk configuration via STDIN: %s" % str(e)

    return config


def run():
    #The Main function that starts the action. The thread will sleep for however many seconds are configured via the Input.
#     config = get_config()
#        
#
#     intervalone = config["intervalone"]
    intervalone =60


    while True:

            weather_Connection(intervalone)
            logging.info("Sleeping for %s seconds" %(intervalone))
            time.sleep(float(intervalone))


if __name__ == '__main__':
    if len(sys.argv) > 1:
        if sys.argv[1] == "--scheme":
            do_scheme()

    else:
        run()    

    sys.exit(0)
4

1 回答 1

0

我已经检查并尝试了您的代码,它工作正常。尝试更换

logging.info("Sleeping for %s seconds" %(intervalone))

print("Sleeping for %s seconds" % (intervalone))

您应该每 6 次预测看到此语句。

注意:为什么从weather_Connection()这里回来

for i, (name, url) in enumerate(sorted(urls.iteritems())):
    response = get_response(conn, url)
    if not response:
        print 'socket timeout on url#%d: %s' % (i, url)
        return
    responses[name] = response 

你可以跳过它continue

for i, (name, url) in enumerate(sorted(urls.iteritems())):
    response = get_response(conn, url)
    if not response:
        print 'socket timeout on url#%d: %s' % (i, url)
        continue
    responses[name] = response
于 2013-08-04T09:32:45.117 回答