Exemplo n.º 1
0
def download_data(from_url, to_localfile):
    '''
	Download a data if nessary.
	Args:
		from_url: URL containing data.
		to_localfile: filename and location where data will be downloaded.
	Raises:
		URLError: When cannot connect to remote server with data.
		HTTPError: When data not found on remote server.
		Exception: For any other reason.
	'''
    if os.path.isfile(to_localfile):
        print(
            f"Data already present in the local directory in file: {to_localfile}."
        )
        return  # download skipped

    print(f"Downloading data...")
    try:
        urlretrieve(from_url, to_localfile)
    except URLError as exc:
        print(f"Cannot connect and download weather data from {from_url}.")
        raise exc
    except HTTPError as exc:
        print(
            f"Connected to the data server but weather data not found at {from_url}."
        )
        raise exc
    except:
        import traceback
        traceback.print_ext()
        raise Exception(f"Data download from {from_url} unsuccesfull.")
Exemplo n.º 2
0
def SendFile(pushfile, contents):

    i = 0
    try:
        fo = open(pushfile+'.result','wt')
        lines = open(pushfile,'rt').readlines()
        for line in lines:
            phone = line.strip().split(',')[0]
            if len(phone) != 11:
                fo.write('phone error[%s]\n', phone)
                continue
            i += 1
            flag = SendSMS(phone, contents)
            if flag:
                fo.write('%5d SendSms[%s] [%s] [ok]\n' % (i, phone, contents))
            else:
                fo.write('%5d SendSms[%s] [%s] [err]\n' % (i, phone, contents))
            if i==1:
                raw_input('please check sms contents, and press any key to continue')
            fo.flush()

        fo.close()
    except:
        traceback.print_ext()
        print "except:",i
Exemplo n.º 3
0
 def evaluate_ct(self):
     try:
         print("Evaluating confirmation time (ECT), pre-notification at " +
               str(self.pre_latch_notif) + " out of " +
               str(self.data.confirmation_updates))
         last_holdoff = self.ct.holdoff
         # reset the timer if no notifications received for a while
         if (self.pre_latch_notif >= self.data.confirmation_updates):
             print("ECT: Reset confirmation time.")
             self.ct.time = 2
             self.ct.holdoff = False
         result = self.ct.update(self.latched_value)
         self.pre_latch_notif += 1
         if self.ct.holdoff:
             announcement = str(
                 (self.ct.delay - self.ct.time) *
                 self.data.confirmation_interval
             ) + " until " + self.data.enumeration[self.latched_value]
             print("ECT: in holdoff, publishing time announcement: " +
                   announcement)
             self.publish("tweeter/time_announce", announcement)
         if last_holdoff and not self.ct.holdoff:
             announcement = "is " + self.data.enumeration[result[1]]
             print("ECT: new value or value restored: " + announcement)
             self.publish("tweeter/time_announce", announcement)
         if result[0]:
             attime = arrow.fromtimestamp(time.time()).to(
                 self.data.timezone).strftime(self.data.time_format)
             self.tweet(
                 self.data.message.format(self.data.enumeration[result[1]],
                                          attime))
     except:
         traceback.print_ext()
         os._exit(1)
Exemplo n.º 4
0
    def _detection_callback_Linux(self, scanner, msg, callback, distinct):
        # Callback for detection on Linux
        # - scanner -- BleakScanner object
        # - msg -- txdbus.message.SignalMessage
        #
        # NOTE: Bluez may not return all every received messages.
        for path, dev in scanner._devices.items():
            # Check address of advertised device
            target_path = None
            if dev["Address"] == self.address:
                target_path = path
                break

        # Received message does not match address
        if not target_path or msg.path != target_path: return

        if msg.member == "PropertiesChanged":
            iface, changed, invalidated = msg.body
            data = changed.get("ManufacturerData", {}).get(725)
            if data is None: return

            data = struct.pack(f"{len(data)}B", *data)
            try: res = self._parse_advertisement(data, distinct)
            except SkipData: pass
            except Exception as e: traceback.print_ext()
            else:
                try: callback(res)
                except Exception as e: traceback.print_exc()
def cmd_executor(cmd):
    p1 = None
    if platform.system() != "Windows":
        try:
            p1 = subprocess.Popen("exec " + cmd, stdout = subprocess.PIPE, stderr=subprocess.PIPE, shell = True)
        except OSError, exc:
            log_error("Error executing command %s\n%s\n" % (cmd, exc));
            import traceback
            traceback.print_ext()
Exemplo n.º 6
0
def Decompression_zip(specific_file):
    """
	Decompression_zip
	"""

    if zipfile.is_zipfile(specific_file):
        try:
            zipfile.ZipFile(specific_file).extractall(
                os.path.split(specific_file)[0])
        except Exception as e:
            traceback.print_ext()
def cmd_executor(cmd):
    p1 = None
    if platform.system() != "Windows":
        try:
            p1 = subprocess.Popen("exec " + cmd,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE,
                                  shell=True)
        except OSError, exc:
            log_error("Error executing command %s\n%s\n" % (cmd, exc))
            import traceback
            traceback.print_ext()
Exemplo n.º 8
0
def _tracebackException(msg, e, skipTop, skipBottom, showException):
    msgs = [msg]
    if showException:
        msgs.append('Exception: %s' % e.__class__.__name__)
    msgs.extend(str(e).split('\n'))
    error(*msgs)
    (t, v, tb) = sys.exc_info()
    if tb is None:
        traceback.print_ext()
    nDumped = 0
    bline = '-' * 60
    tbOut = traceback.extract_tb(tb)
    if skipTop:
        tbOut = tbOut[skipTop:]
    if skipBottom:
        tbOut = tbOut[:-skipBottom]
    for (pathFile, numLine, nameFunc, text) in tbOut:
        if nDumped == maxTracebackLines:
            info('%s----- traceback truncated -----' % ('  ' * nDumped))
            break
        if pathFile == '<string>':
            s = 'line %d:' % numLine
        else:
            s = '%s:%d' % (os.path.split(pathFile)[1], numLine)
        if nameFunc and nameFunc != '?':
            s += ' %s()' % nameFunc
        if text:
            s += ' "%s"' % text
        if nDumped == 0:
            info(bline)
        sOut = '%s%s' % ('  ' * nDumped, s)
        if len(sOut) > maxWidth:
            if text:
                sOut = '%s..."' % sOut[:maxWidth-1]
            else:
                sOut = '%s...' % sOut[:maxWidth]
        info(sOut)
        nDumped += 1
    if nDumped > 0:
        info(bline)
    del tb
Exemplo n.º 9
0
			if (header.mode == ICAPHeader.Reqmod):
				handler = ReqmodHandler(header, br)

			if (header.mode == ICAPHeader.Respmod):
				handler = RespmodHandler(header, br)

			try:
				handler.modify()
				log.log('Modified ' + str(no))
			except BaseException, e:
				traceback.print_exc()
				log.log('Handler Error: ' + str(e))

				strio = StringIO()
				traceback.print_ext(fileobj=strio)
				log.log(strio.getvalue())

			connSock.send(str(handler))
			log.log('Sent ' + header.mode + ' response back to ' + str(addr))
			log.verboselog(str(handler))
		except socket.error, e:
			log.log('Socket Error: ' + str(e))
		except KeyboardInterrupt:
			raise
		except BaseException, e:
			log.log('Error: ' + str(e))
			needreconnect = True
		finally:
			connSock.close()
			log.log('Closing #' + str(no) + ' connSock...')