473,289 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

Issue with return statement inside except of for

I have this code inside a function:

Expand|Select|Wrap|Line Numbers
  1. try:
  2.         for linea in subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).stdout:
  3.                 req = urllib2.Request(URL, "&mac_addr=" + mac_addr + " &sampled_time=" + sampled_time + " &line_data=" + linea)
  4.                 ret = urllib2.urlopen(req).read()
  5. except (urllib2.URLError, httplib.HTTPException):
  6.         logger.error('Error de comunicación con el servidor remoto')
  7.         return
  8. else:
  9.         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.

Expand|Select|Wrap|Line Numbers
  1. 2007-10-16 19:40:04,237 Demonio DEBUG    Programa iniciado
  2. 2007-10-16 19:40:04,424 Demonio ERROR    Error de comunicación con el servidor remoto
  3. 2007-10-16 19:40:05,681 Demonio ERROR    Error de comunicación con el servidor remoto
  4. 2007-10-16 19:40:06,719 Demonio ERROR    Error de comunicación con el servidor remoto
  5. 2007-10-16 19:40:07,751 Demonio ERROR    Error de comunicación con el servidor remoto
  6. 2007-10-16 19:40:08,933 Demonio ERROR    Error de comunicación con el servidor remoto
  7. 2007-10-16 19:40:12,573 Demonio ERROR    Error de comunicación con el servidor remoto
  8. 2007-10-16 19:40:13,605 Demonio ERROR    Error de comunicación con el servidor remoto
  9. 2007-10-16 19:40:15,713 Demonio ERROR    Error de comunicación con el servidor remoto
  10. 2007-10-16 19:40:17,526 Demonio ERROR    Error de comunicación con el servidor remoto
  11. 2007-10-16 19:40:18,608 Demonio ERROR    Error de comunicación con el servidor remoto
  12. 2007-10-16 19:40:19,831 Demonio ERROR    Error de comunicación con el servidor remoto
  13. 2007-10-16 19:40:24,892 Demonio ERROR    Error de comunicación con el servidor remoto
  14. 2007-10-16 19:40:27,172 Demonio ERROR    Error de comunicación con el servidor remoto
  15. 2007-10-16 19:40:30,581 Demonio ERROR    Error de comunicación con el servidor remoto
  16. 2007-10-16 19:40:31,643 Demonio ERROR    Error de comunicación con el servidor remoto
  17. 2007-10-16 19:40:32,788 Demonio ERROR    Error de comunicación con el servidor remoto
  18. 2007-10-16 19:40:34,201 Demonio ERROR    Error de comunicación con el servidor remoto
  19. 2007-10-16 19:40:35,663 Demonio ERROR    Error de comunicación con el servidor remoto
  20. 2007-10-16 19:40:36,698 Demonio ERROR    Error de comunicación con el servidor remoto
  21. 2007-10-16 19:40:37,739 Demonio ERROR    Error de comunicación con el servidor remoto
  22. 2007-10-16 19:40:38,773 Demonio ERROR    Error de comunicación con el servidor remoto
  23. 2007-10-16 19:40:39,834 Demonio ERROR    Error de comunicación con el servidor remoto
  24. 2007-10-16 19:40:42,007 Demonio ERROR    Error de comunicación con el servidor remoto
  25. 2007-10-16 19:40:43,063 Demonio ERROR    Error de comunicación con el servidor remoto
  26. 2007-10-16 19:40:44,099 Demonio ERROR    Error de comunicación con el servidor remoto
  27. 2007-10-16 19:40:45,153 Demonio ERROR    Error de comunicación con el servidor remoto
  28. 2007-10-16 19:40:46,444 Demonio ERROR    Error de comunicación con el servidor remoto
  29. 2007-10-16 19:40:49,240 Demonio ERROR    Error de comunicación con el servidor remoto
  30. 2007-10-16 19:40:50,310 Demonio ERROR    Error de comunicación con el servidor remoto
  31. 2007-10-16 19:40:51,352 Demonio ERROR    Error de comunicación con el servidor remoto
  32. 2007-10-16 19:40:52,393 Demonio ERROR    Error de comunicación con el servidor remoto
  33. 2007-10-16 19:40:53,443 Demonio ERROR    Error de comunicación con el servidor remoto
  34. 2007-10-16 19:40:54,492 Demonio ERROR    Error de comunicación con el servidor remoto
  35. 2007-10-16 19:40:55,649 Demonio ERROR    Error de comunicación con el servidor remoto
  36. 2007-10-16 19:40:56,714 Demonio ERROR    Error de comunicación con el servidor remoto
  37. 2007-10-16 19:40:57,766 Demonio ERROR    Error de comunicación con el servidor remoto
  38. 2007-10-16 19:40:58,803 Demonio ERROR    Error de comunicación con el servidor remoto
  39. 2007-10-16 19:40:59,853 Demonio ERROR    Error de comunicación con el servidor remoto
  40. 2007-10-16 19:41:00,906 Demonio ERROR    Error de comunicación con el servidor remoto
  41. 2007-10-16 19:41:02,049 Demonio ERROR    Error de comunicación con el servidor remoto
  42. 2007-10-16 19:41:03,404 Demonio ERROR    Error de comunicación con el servidor remoto
  43. 2007-10-16 19:41:07,259 Demonio ERROR    Error de comunicación con el servidor remoto
  44. 2007-10-16 19:41:08,353 Demonio ERROR    Error de comunicación con el servidor remoto
  45. 2007-10-16 19:41:09,393 Demonio ERROR    Error de comunicación con el servidor remoto
  46. 2007-10-16 19:41:10,426 Demonio ERROR    Error de comunicación con el servidor remoto
  47. 2007-10-16 19:41:11,460 Demonio ERROR    Error de comunicación con el servidor remoto
  48. 2007-10-16 19:41:13,056 Demonio ERROR    Error de comunicación con el servidor remoto
  49. 2007-10-16 19:45:02,167 Demonio INFO     Datos enviados correctamente
  50. 2007-10-16 19:48:05,953 Demonio INFO     Datos enviados correctamente
  51. 2007-10-16 19:50:48,014 Demonio INFO     Datos enviados correctamente
  52. 2007-10-16 19:51:57,637 Demonio ERROR    Error de comunicación con el servidor remoto
  53. 2007-10-16 19:52:30,410 Demonio INFO     Datos enviados correctamente
  54. 2007-10-16 19:53:12,558 Demonio INFO     Datos enviados correctamente
  55. 2007-10-16 19:54:09,003 Demonio INFO     Datos enviados correctamente
  56. 2007-10-16 19:54:53,073 Demonio INFO     Datos enviados correctamente
  57. 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)
Oct 17 '07 #1
5 1126
bartonc
6,596 Expert 4TB
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.
Oct 17 '07 #2
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 :) )


Expand|Select|Wrap|Line Numbers
  1. # -*- coding: cp1252 -*-
  2. import sys, urllib, urllib2, commands, os, datetime, ConfigParser, signal
  3. import string, time, logging, logging.handlers, subprocess
  4. import httplib, inspect
  5.  
  6. def signal_hand(signum, singhand):
  7.         logger.debug('Ejecución terminada por el sistema. SIGNAL:' + str(signum))
  8.         exit()
  9.  
  10. def getMacAddress():
  11.         if sys.platform.lower().startswith('win'):
  12.                 for line in subprocess.Popen("ipconfig /all", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).stdout:
  13.                         if line.lstrip().startswith("Dirección física"):
  14.                                 mac = line.split(':')[1].strip().replace('-',':')
  15.                                 break
  16.         if sys.platform.lower().startswith('lin'):
  17.                 for line in subprocess.Popen("ifconfig", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).stdout:
  18.                         if line.find('Ether') > -1:
  19.                                 mac = line.split()[4]
  20.                                 break
  21.         return mac
  22.  
  23. def principito(URL):
  24.         sampled_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  25.  
  26.         print "Enviando diagnóstico de red a " + URL
  27.         print "Desde MAC " , mac_addr , "a la fecha/hora " + sampled_time
  28.  
  29.         try:
  30.                 for linea in subprocess.Popen(comando, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).stdout:
  31.                         req = urllib2.Request(URL, "&mac_addr=" + mac_addr + " &sampled_time=" + sampled_time + " &line_data=" + linea)
  32.                         ret = urllib2.urlopen(req).read()
  33.         except (urllib2.URLError, httplib.HTTPException):
  34.                 logger.error('Error de comunicación con el servidor remoto')
  35.                 print 'Error de comunicación con el servidor remoto.\n'
  36.                 return
  37.         else:
  38.                 print 'Done.\n'
  39.                 logger.info('Datos enviados correctamente')
  40.  
  41.  
  42. # -------- ************** --------
  43. # -------- HILO PRINCIPAL --------
  44. # -------- ************** --------
  45.  
  46. times_sent = 1
  47. conf_path = sys.path[0]
  48. conf_name = 'config.ini'
  49.  
  50. # Seteo el Logger para que no muestre nada en consola, y registre todos los eventos en el disco
  51. handler_console = logging.StreamHandler()
  52. handler_console.setLevel(60)
  53. root_logger = logging.getLogger('')
  54. root_logger.setLevel(logging.NOTSET)
  55. root_logger.addHandler(handler_console)
  56.  
  57. try:
  58.         config = ConfigParser.ConfigParser()
  59.         config.read( os.path.join(conf_path, conf_name))
  60.  
  61.         # Inicializo el logger, y lo guardo en la misma carpeta que el programa y el archivo de configuracion
  62.         logger = logging.getLogger('Demonio')
  63.         hand_arch = logging.handlers.RotatingFileHandler(
  64.                 os.path.join(conf_path , config.get('logfile','name')),
  65.                 'a',
  66.                 1024 * config.getint('logfile','maxsize'),
  67.                 config.getint('logfile','backup'),)
  68.         hand_arch.setLevel(logging.NOTSET)
  69.         hand_arch.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)-8s %(message)s'))
  70.         logger.addHandler(hand_arch)
  71. except Exception:
  72.         print 'Error en el archivo de configuracion'
  73.         print sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1])
  74.         print sys.exc_info()[0].__doc__
  75.         exit()
  76.  
  77. # Comienzo a loguear
  78. logger.debug('Programa iniciado')
  79.  
  80. # Guardo la MAC en el archivo config para no ejecutarlo constantemente
  81. if not config.has_section("xo info"):
  82.         config.add_section("xo info")
  83.  
  84. try:
  85.         comando = config.get("xo info", "comando")
  86. except:
  87.         print 'Error en el archivo de configuracion'
  88.         print sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1])
  89.         print sys.exc_info()[0].__doc__
  90.         exit()
  91.  
  92. if config.has_option("xo info", "mac"):
  93.         mac_addr = config.get("xo info", "mac")
  94. else:
  95.         try:
  96.                 mac_addr = getMacAddress()
  97.         except:
  98.                 print 'No se pudo determinar la MAC, se cancela la ejecución'
  99.                 logger.critical('No se pudo determinar la MAC, se cancela la ejecución')
  100.                 exit()
  101.         else:
  102.                 config.set("xo info","mac", mac_addr)
  103.  
  104. config.write( file( os.path.join(conf_path, conf_name) ,'w') )
  105.  
  106. # Loguear las terminaciones desde el sistema (term, hup)
  107. # El TRY es necesario para que funque en Windows nomás.
  108. try:
  109.         signal.signal(signal.SIGTERM, signal_hand)
  110.         signal.signal(signal.SIGHUP, signal_hand)
  111. except:
  112.         pass
  113.  
  114.  
  115.  
  116. send_time = config.getfloat("host", "send_time")
  117. URL = config.get("host", "addr")
  118.  
  119. # Bucle principal
  120.  
  121. try:
  122.         while True: 
  123.                 print "__ Ejecucion N " , times_sent, " de el 'Demonio Posteador'__"
  124.                 principito(URL)
  125.                 times_sent += 1
  126.                 time.sleep(send_time)
  127. except KeyboardInterrupt:
  128.         print "\n< ... --- ... >"
  129.         print "Ejecucion terminada por el usuario. :( \nEsperamos que no se hayan perdido datos! Good bye!"
  130.         print "..............."
  131.         logger.warning('Ejecución terminada por el usuario')
  132.         exit()
  133. except SystemExit:
  134.         exit()
  135. except:
  136.         print "\n........................."
  137.         print "Error inesperado en tiempo de ejecucion"
  138.         print "Se ha logueado la informacion de error. Intentando retomar ejecución"
  139.         print ".........................\n"
  140.         logger.critical(sys.exc_info()[0].__module__ + ' -> ' + str(sys.exc_info()[1]))
Oct 17 '07 #3
bartonc
6,596 Expert 4TB
It looks like
Expand|Select|Wrap|Line Numbers
  1. #
  2.                 time.sleep(send_time)
is set to once per second, not minute. You may want to try
Expand|Select|Wrap|Line Numbers
  1. #
  2. #
  3.                 time.sleep(send_time * 60)
Oct 17 '07 #4
Yes... that's it. OMG, I feel so silly right now, what a dumb mistake !!

Thanks a lot!
Oct 18 '07 #5
bartonc
6,596 Expert 4TB
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).
Oct 18 '07 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

17
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...
15
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...
15
by: Nerox | last post by:
Hi, If i write: #include <stdio.h> int foo(int); int main(void){ int a = 3; foo(a); }
2
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....
5
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....
8
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...
5
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...
0
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:...
3
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...
2
isladogs
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...
0
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...
0
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...
0
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...
0
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 =...
0
isladogs
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...
0
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...
0
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...
1
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)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.