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 1140 bartonc 6,596
Recognized Expert Expert
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]))
bartonc 6,596
Recognized Expert Expert
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!
bartonc 6,596
Recognized Expert Expert
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
Set rs = Me.RecordsetClone
rs.Find "=" & lngContractID
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
I must site the Heisenberb Uncertainty Principal here, as it
|
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 i = 0,j;
j = sample(0);
|
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.
Everything runs pretty well except for a 3rd party dll
that is called when certain restricted aspx pages are
loaded to perform a 2 factor authentication that throws a
runtime error on line 105 'x' is not defined every time
it is enabled when...
|
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.
Basically I need to assemble an identifier like
| |
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 (SqlCommand cm = new SqlCommand("ItemCount", cn)) {
cm.CommandType = CommandType.StoredProcedure;
|
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 populates the
box. Next I added functionality to add data. This adds data to the DB
and then forces the listbox to refresh by clearing it's contents and
then re-running the populate code.
However, when I add an item and do the refresh, the listbox...
|
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: http://docs.python.org/lib/module-timeit.html
Second of all the number of subtractions is not that different between
the two variants of your functions. back_diff_one does 75360
subtractions per call while back_diff_two does 76800, these two
numbers are almost the same. It's...
|
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 written in concatinated string format (provided below).
when i execute the procedure on my clients database some concatinated
lines in the select statement are not considered.(i.e the select statement is executed without those two line between the...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |