I have this code inside a function: - try:
-
for linea in subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).stdout:
-
req = urllib2.Request(URL, "&mac_addr=" + mac_addr + " &sampled_time=" + sampled_time + " &line_data=" + linea)
-
ret = urllib2.urlopen(req).read()
-
except (urllib2.URLError, httplib.HTTPException):
-
logger.error('Error de comunicación con el servidor remoto')
-
return
-
else:
-
logger.info('Datos enviados correctamente')
My problem is that this function is called once per minute, BUT if an error occurs the logger logs several "Error...", in consecutives times, less than a second. - 2007-10-16 19:40:04,237 Demonio DEBUG Programa iniciado
-
2007-10-16 19:40:04,424 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:05,681 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:06,719 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:07,751 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:08,933 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:12,573 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:13,605 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:15,713 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:17,526 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:18,608 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:19,831 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:24,892 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:27,172 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:30,581 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:31,643 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:32,788 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:34,201 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:35,663 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:36,698 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:37,739 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:38,773 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:39,834 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:42,007 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:43,063 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:44,099 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:45,153 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:46,444 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:49,240 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:50,310 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:51,352 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:52,393 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:53,443 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:54,492 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:55,649 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:56,714 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:57,766 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:58,803 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:40:59,853 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:00,906 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:02,049 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:03,404 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:07,259 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:08,353 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:09,393 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:10,426 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:11,460 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:41:13,056 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:45:02,167 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:48:05,953 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:50:48,014 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:51:57,637 Demonio ERROR Error de comunicación con el servidor remoto
-
2007-10-16 19:52:30,410 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:53:12,558 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:54:09,003 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:54:53,073 Demonio INFO Datos enviados correctamente
-
2007-10-16 19:55:41,263 Demonio INFO Datos enviados correctamente
My "expected behavior" is that log "Error... " only once, and with the "return" statemente jumps back to the main program.
What's going wrong? :/
(sorry about my poor english) 5 1126
It is possible that the "once per minute" delay is built into this function, not the calling function.
Please post the entire function so the we may see what is being skipped by return.
It is possible that the "once per minute" delay is built into this function, not the calling function.
Please post the entire function so the we may see what is being skipped by return.
Here is the entire .py file, isn't so long so i decided to post it complete. Hope you can help me, thanks in advance :)
(also hope that the "spanish locale" wasn't a problem to debug :) ) - # -*- coding: cp1252 -*-
-
import sys, urllib, urllib2, commands, os, datetime, ConfigParser, signal
-
import string, time, logging, logging.handlers, subprocess
-
import httplib, inspect
-
-
def signal_hand(signum, singhand):
-
logger.debug('Ejecución terminada por el sistema. SIGNAL:' + str(signum))
-
exit()
-
-
def getMacAddress():
-
if sys.platform.lower().startswith('win'):
-
for line in subprocess.Popen("ipconfig /all", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).stdout:
-
if line.lstrip().startswith("Dirección física"):
-
mac = line.split(':')[1].strip().replace('-',':')
-
break
-
if sys.platform.lower().startswith('lin'):
-
for line in subprocess.Popen("ifconfig", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).stdout:
-
if line.find('Ether') > -1:
-
mac = line.split()[4]
-
break
-
return mac
-
-
def principito(URL):
-
sampled_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
-
print "Enviando diagnóstico de red a " + URL
-
print "Desde MAC " , mac_addr , "a la fecha/hora " + sampled_time
-
-
try:
-
for linea in subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).stdout:
-
req = urllib2.Request(URL, "&mac_addr=" + mac_addr + " &sampled_time=" + sampled_time + " &line_data=" + linea)
-
ret = urllib2.urlopen(req).read()
-
except (urllib2.URLError, httplib.HTTPException):
-
logger.error('Error de comunicación con el servidor remoto')
-
print 'Error de comunicación con el servidor remoto.\n'
-
return
-
else:
-
print 'Done.\n'
-
logger.info('Datos enviados correctamente')
-
-
-
# -------- ************** --------
-
# -------- HILO PRINCIPAL --------
-
# -------- ************** --------
-
-
times_sent = 1
-
conf_path = sys.path[0]
-
conf_name = 'config.ini'
-
-
# Seteo el Logger para que no muestre nada en consola, y registre todos los eventos en el disco
-
handler_console = logging.StreamHandler()
-
handler_console.setLevel(60)
-
root_logger = logging.getLogger('')
-
root_logger.setLevel(logging.NOTSET)
-
root_logger.addHandler(handler_console)
-
-
try:
-
config = ConfigParser.ConfigParser()
-
config.read( os.path.join(conf_path, conf_name))
-
-
# Inicializo el logger, y lo guardo en la misma carpeta que el programa y el archivo de configuracion
-
logger = logging.getLogger('Demonio')
-
hand_arch = logging.handlers.RotatingFileHandler(
-
os.path.join(conf_path , config.get('logfile','name')),
-
'a',
-
1024 * config.getint('logfile','maxsize'),
-
config.getint('logfile','backup'),)
-
hand_arch.setLevel(logging.NOTSET)
-
hand_arch.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)-8s %(message)s'))
-
logger.addHandler(hand_arch)
-
except Exception:
-
print 'Error en el archivo de configuracion'
-
print sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1])
-
print sys.exc_info()[0].__doc__
-
exit()
-
-
# Comienzo a loguear
-
logger.debug('Programa iniciado')
-
-
# Guardo la MAC en el archivo config para no ejecutarlo constantemente
-
if not config.has_section("xo info"):
-
config.add_section("xo info")
-
-
try:
-
comando = config.get("xo info", "comando")
-
except:
-
print 'Error en el archivo de configuracion'
-
print sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1])
-
print sys.exc_info()[0].__doc__
-
exit()
-
-
if config.has_option("xo info", "mac"):
-
mac_addr = config.get("xo info", "mac")
-
else:
-
try:
-
mac_addr = getMacAddress()
-
except:
-
print 'No se pudo determinar la MAC, se cancela la ejecución'
-
logger.critical('No se pudo determinar la MAC, se cancela la ejecución')
-
exit()
-
else:
-
config.set("xo info","mac", mac_addr)
-
-
config.write( file( os.path.join(conf_path, conf_name) ,'w') )
-
-
# Loguear las terminaciones desde el sistema (term, hup)
-
# El TRY es necesario para que funque en Windows nomás.
-
try:
-
signal.signal(signal.SIGTERM, signal_hand)
-
signal.signal(signal.SIGHUP, signal_hand)
-
except:
-
pass
-
-
-
-
send_time = config.getfloat("host", "send_time")
-
URL = config.get("host", "addr")
-
-
# Bucle principal
-
-
try:
-
while True:
-
print "__ Ejecucion N " , times_sent, " de el 'Demonio Posteador'__"
-
principito(URL)
-
times_sent += 1
-
time.sleep(send_time)
-
except KeyboardInterrupt:
-
print "\n< ... --- ... >"
-
print "Ejecucion terminada por el usuario. :( \nEsperamos que no se hayan perdido datos! Good bye!"
-
print "..............."
-
logger.warning('Ejecución terminada por el usuario')
-
exit()
-
except SystemExit:
-
exit()
-
except:
-
print "\n........................."
-
print "Error inesperado en tiempo de ejecucion"
-
print "Se ha logueado la informacion de error. Intentando retomar ejecución"
-
print ".........................\n"
-
logger.critical(sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1]))
It looks like
is set to once per second, not minute. You may want to try - #
-
#
-
time.sleep(send_time * 60)
Yes... that's it. OMG, I feel so silly right now, what a dumb mistake !!
Thanks a lot!
Yes... that's it. OMG, I feel so silly right now, what a dumb mistake !!
Thanks a lot!
Which makes me feel pretty sharp-eyed (and almost multi-lingual).
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Danny J. Lesandrini |
last post by:
The following code works with a standard MDB to navigate
to a particluar record (with a DAO recordset, of course)
but it's giving me problems in an ADP I'm working on.
Dim rs As ADODB.Recordset...
|
by: Greenhorn |
last post by:
Hi,
when a function doesn't specify a return type ,value what value is
returned. In the below programme, the function sample()is returning the
value passed to 'k'.
sample(int);
main()
{
int...
|
by: Nerox |
last post by:
Hi, If i write:
#include <stdio.h>
int foo(int);
int main(void){
int a = 3;
foo(a);
}
|
by: K.C. Brown |
last post by:
I'm trying to finish up an app that uses a left and right
frame extensively. The left frame contains a dynamically
built menu and the right is used as the target for links
selected from the left....
|
by: Uwe C. Schroeder |
last post by:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
maybe my mind is stuck, but here's something strange.
This is the classic "counter" thing, where you can't / won't use sequences....
|
by: Andrew Robinson |
last post by:
Are these two equivalent? Is one better than the other? I tend to go with #1
but started wondering....
Thanks,
1:
using (SqlConnection cn = new SqlConnection(DataConnection))
using...
|
by: heddy |
last post by:
I have a listbox that gets populated in code by a reader result set
from a stored proc on SQL Server 2005. In building this I created a
set of test rows in the DB and the code runs fine and...
|
by: Daniel Fetchinson |
last post by:
I've written up a stripped down version of the code. I apologize for the bad
First of all, your method of timing is not the best. Use the timeit
module instead:...
|
by: Vish4u |
last post by:
Hello Everyone,
I have a encountered a strange issue with the execution of my stored procedure on clients machine.
My stored procedure contains a cursor in which there is a select statement...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM).
In this month's session, the creator of the excellent VBE...
|
by: DolphinDB |
last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation.
Take...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: Aftab Ahmad |
last post by:
Hello Experts!
I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
|
by: Aftab Ahmad |
last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below.
Dim IE As Object
Set IE =...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: marcoviolo |
last post by:
Dear all,
I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
| |