473,698 Members | 2,334 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Issue with return statement inside except of for

19 New Member
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 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.
Oct 17 '07 #2
diegososa
19 New Member
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 Recognized Expert Expert
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
diegososa
19 New Member
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 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).
Oct 18 '07 #6

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

Similar topics

17
4212
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
15
6725
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);
15
2799
by: Nerox | last post by:
Hi, If i write: #include <stdio.h> int foo(int); int main(void){ int a = 3; foo(a); }
2
1322
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...
5
2335
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
8
3375
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;
5
2298
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...
0
135
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...
3
1525
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...
0
8674
marktang
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...
0
9157
Oralloy
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...
0
9027
jinu1996
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...
1
8895
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,...
0
7725
agi2029
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...
1
6518
isladogs
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...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
2
2329
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.