我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用time.localtime()。
def flush_queue(self): # check number of messages in queue num_log_entries = self.log_queue.qsize() if num_log_entries > 0: # open the log file with open(self.log_full_filename, 'ab') as log_file: for i in range(num_log_entries): log_entry = self.log_queue.get() # append extra log information current_time = log_entry['time'] current_time_str = time.asctime(time.localtime(current_time)) log_entry['localtime'] = current_time_str # log the message as a JSON string if isPython3: log_file.write(bytes(json.dumps(log_entry) + "\n", 'UTF-8')) else: log_file.write(json.dumps(log_entry) + "\n")
def log(log_subsys, log_message, log_type='info', log_data=None): current_time = time.time() # form log entry dictionary log_entry = { 'time' : current_time, 'subsys' : log_subsys, 'type' : log_type, 'message' : log_message, } if log_data is not None: log_dict = dict(log_entry, **log_data) else: log_dict = log_entry if Logger.debug: print("LOG {:s} | {:s}".format(time.strftime("%H:%M:%S", time.localtime(current_time)), log_message)) # attempt to place in queue try: Logger.log_queue.put(log_dict) except Queue.Full as e: sys.stderr.write('Warning: log queue full, discarding message: "{:s}"\n'.format(log_message))
def formatTime(self, record, datefmt=None): """ Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the ISO8601 format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the 'converter' attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the 'converter' attribute in the Formatter class. """ ct = self.converter(record.created) if datefmt: s = time.strftime(datefmt, ct) else: t = time.strftime("%Y-%m-%d %H:%M:%S", ct) s = "%s,%03d" % (t, record.msecs) return s
def disconnect(self): flag = self.get_conn() if len(flag) == 1: handle = flag[0][0] dialname = str(flag[0][1]) try: win32ras.HangUp(handle) self.saveData(False, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) logger.info("??" + dialname + "????") return True except Exception as e: logger.info(dialname + "???????" + str(e.message)) # disconnect() else: logger.info("?????????????") # ????????
def __built_table(self): """ ?? :return: """ self.execute(""" CREATE TABLE test_results ( case_id INTEGER PRIMARY KEY, case_name TEXT, device_name TEXT, cpu_list TEXT, mem_list TEXT, execution_status TEXT, created_time DATETIME DEFAULT (datetime('now', 'localtime')) );""")
def mkdir_file(self): """ :return:????????? """ ini = U.ConfigIni() result_file = str(ini.get_ini('test_case', 'log_file')) result_file_every = result_file + '/' + \ time.strftime("%Y-%m-%d_%H_%M_%S{}".format(random.randint(10, 99)), time.localtime(time.time())) file_list = [ result_file, result_file_every, result_file_every + '/log', result_file_every + '/per', result_file_every + '/img', result_file_every + '/status'] if not os.path.exists(result_file): os.mkdir(result_file) for file_path in file_list: if not os.path.exists(file_path): os.mkdir(file_path) return result_file_every
def log(scan_type,host,port,info=''): mutex.acquire() time_str = time.strftime('%X', time.localtime( time.time())) if scan_type == 'portscan': print "[%s] %s:%d open"%(time_str,host,int(port)) elif scan_type == 'discern': print "[%s] %s:%d is %s"%(time_str,host,int(port),info) elif scan_type == 'active': print "[%s] %s active" % (time_str, host) elif info: log = "[*%s] %s:%d %s %s"%(time_str,host,int(port),scan_type,info) print log log_file = open('result.log','a') log_file.write(log+"\r\n") log_file.close() mutex.release()
def asctime(t=None): """ Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: >>> asctime(time.gmtime(0)) 'Thu Jan 1 00:00:00 1970' If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime(). This is meant to normalise the output of the built-in time.asctime() across different platforms and Python versions. In Python 3.x, the day of the month is right-justified, whereas on Windows Python 2.7 it is padded with zeros. See https://github.com/behdad/fonttools/issues/455 """ if t is None: t = time.localtime() s = "%s %s %2s %s" % ( DAYNAMES[t.tm_wday], MONTHNAMES[t.tm_mon], t.tm_mday, time.strftime("%H:%M:%S %Y", t)) return s
def gethtml(zurl,str_fname): mobileEmulation = {'deviceName': 'Apple iPhone 6'} options = webdriver.ChromeOptions() options.add_experimental_option('mobileEmulation', mobileEmulation) driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options) driver.get(zurl) time.sleep(5) result = [] # for i in range(0,300): #???0?20?????i? for i in range(0, 1): # ???0?3?????i? print('????' + str(i)) myscroll(driver) time.sleep(2) st=time.strftime("%Y%m%d",time.localtime()) # print(driver.page_source, file=open('itg201703.html', 'w', encoding='utf-8')) print(driver.page_source, file=open(str_fname+"-"+st+".html", 'w', encoding='utf-8')) print("?????????") print(driver.title) driver.quit()
def get_merged_nodes(): merged = {} mergeddmp = open(args.infile_mergeddmp_path,'r') for curr_line in mergeddmp: curr_line_old_taxid = curr_line.split('|')[0].strip() curr_line_new_taxid = curr_line.split('|')[1].strip() merged[curr_line_old_taxid] = curr_line_new_taxid mergeddmp.close() log_file = open(args.logfile_path, 'a') log_file.write('get_merged_nodes() finished ' + strftime("%H:%M:%S on %d-%m-%Y",localtime()) + '\n') log_file.close() return(merged) #################################################
def get_deleted_nodes(): deleted = {} delnodesdmp = open(args.infile_delnodesdmp_path,'r') for curr_line in delnodesdmp: curr_line_old_taxid = curr_line.split('|')[0].strip() deleted[curr_line_old_taxid] = True delnodesdmp.close() log_file = open(args.logfile_path, 'a') log_file.write('get_deleted_nodes() finished ' + strftime("%H:%M:%S on %d-%m-%Y",localtime()) + '\n') log_file.close() return(deleted) #################################################
def print_log(msg, print_flag = True): """ Parameters ---------- msg print_flag Returns ------- """ if print_flag: if type(msg) is str: print ('%s | ' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()))) + msg else: print '%s | %r' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()), msg) sys.stdout.flush()
def main(argv): dir_ = argv[1] for entry in sorted(os.listdir(dir_)): path = os.path.join(dir_, entry) size = os.path.getsize(path) mtime = os.path.getmtime(path) mtime_format = time.strftime("%b %d %H:%M", time.localtime(mtime)) reset = '\033[0m' if os.path.isdir(path): color = '\033[1;94m' elif os.access(path, os.X_OK): color = '\033[1;92m' else: color = '' senf.print_("%6d %13s %s%s%s" % (size, mtime_format, color, entry, reset))
def trickit(self,num): for j in range(num,0,-1): #self.Label1["text"]=j minutes = int(j / 60) seconds = j % 60 label_text = str(minutes) + '??' + str(seconds) + '?' #self.label["text"]= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) self.label["text"]= label_text self.root.update() time.sleep(1) self.root.quit self.root.destroy() del self.root #????????????? #test #screen_saver = ScreenSaver() #screen_saver.run()
def Time2Internaldate(date_time): """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time) Convert 'date_time' to IMAP4 INTERNALDATE representation.""" if isinstance(date_time, (int, float)): tt = time.localtime(date_time) elif isinstance(date_time, (tuple, time.struct_time)): tt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' % ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] + divmod(zone//60, 60)))
def createCsvFile(confFrame): createCsvDir() stationName = confFrame.stations[0].stn prettyDate = time.strftime("%Y%m%d_%H%M%S", time.localtime()) csvFileName = "{}_{}.csv".format(prettyDate, stationName.rstrip()) csv_path = "{}/{}".format(CSV_DIR, csvFileName) if (os.path.isfile(csv_path)): nextIndex = getNextIndex(csv_path) csvFileName = "{}_{}.csv".format(prettyDate, nextIndex) csv_path = "{}/{}".format(CSV_DIR, csvFileName) csv_handle = open(csv_path, 'w') csv_handle.write("Timestamp") for ch in confFrame.stations[0].channels: csv_handle.write(",{}".format(ch.rstrip())) if ch.rstrip() != '' else None csv_handle.write(",Freq") csv_handle.write(",ROCOF") csv_handle.write("\n") return csv_handle
def user_insert(self, nm, pw): cmd = "SELECT USERNAME, PASSWORD FROM USERS" map_value = self._db.execute(cmd) dic = dict(map_value) if nm in dic.keys(): return None, 1 cmd = "INSERT INTO USERS (USERNAME, PASSWORD, NICKNAME, AVATARNAME) VALUES ('{0}', '{1}', '{2}', '{3}')".format(nm, pw, nm, "") self._db.execute(cmd) self._db.commit() cmd = "SELECT * FROM USERS" list_value = self._db.execute(cmd) for ind, name, nickname, avatar_name, password in list_value: if name == nm: dic = {"userID": ind, "name": name, "password": password, "nickname": nickname, "avatarName": avatar_name} current_time = time.localtime() str_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time) self.insert_message(SYSTEM_BROADCAST, 0, ind, str_time, "????Paper Melody!!") return dic, 0 return None, 1
def __init__(self,lexer=None): if lexer is None: lexer = lex.lexer self.lexer = lexer self.macros = { } self.path = [] self.temp_path = [] # Probe the lexer for selected tokens self.lexprobe() tm = time.localtime() self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm)) self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm)) self.parser = None # ----------------------------------------------------------------------------- # tokenize() # # Utility function. Given a string of text, tokenize into a list of tokens # -----------------------------------------------------------------------------
def rst_id(self, rst_id): """ Sets the run status of this node. :param int rst_id: The new run status for this node. """ old_rst_id = self.rst_id self.__rst_id_wrapper(rst_id) # Update the start datetime of this node. if rst_id == C.ENK_RST_ID_RUNNING: if not self._rnd_datetime_start: self._rnd_datetime_start = strftime("%Y-%m-%d %H:%M:%S", localtime()) self._rnd_datetime_stop = None # Update the stop datetime of this node. if old_rst_id != rst_id and rst_id in (C.ENK_RST_ID_COMPLETED, C.ENK_RST_ID_ERROR): self._rnd_datetime_stop = strftime("%Y-%m-%d %H:%M:%S", localtime()) # ------------------------------------------------------------------------------------------------------------------
def __history_get(self,history,item_ID,time_from,time_till): ''' ???? ???? item ??????? history ? ''' history_data=[] history_data[:]=[] response=self.zapi.history.get({ "time_from":time_from, "time_till":time_till, "output": "extend", "history": history, "itemids": item_ID, "sortfield":"clock", "limit": 10080 }) if len(response) == 0: warn_msg("not have history_data") debug_info=str([history,item_ID,time_from,time_till,"####not have history_data"]) self.logger.debug(debug_info) return 0.0 for history_info in response: timeArray = time.localtime(int(history_info['clock'])) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print(item_ID,history_info['value'],otherStyleTime)
def next_time(time_string): try: parsed = list(time.strptime(time_string, "%H:%M")) except (TypeError, ValueError): return float(time_string) now = time.localtime() current = list(now) current[3:6] = parsed[3:6] current_time = time.time() delta = time.mktime(current) - current_time if delta <= 0.0: current[2] += 1 return time.mktime(current) - current_time return delta
def store(self, out, header=""): """ Write the properties list to the stream 'out' along with the optional 'header' """ if out.mode[0] != 'w': raise ValueError('Steam should be opened in write mode!') try: #out.write(''.join(('#',header,'\n'))) # Write timestamp #tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime()) #out.write(''.join(('#',tstamp,'\n'))) # Write properties from the pristine dictionary for key, value in sorted(self._origprops.items()): line = ''.join((key,'=',self.escape(value))) if not line.endswith('\n'): line += '\n' out.write(line) out.close() except IOError as e: raise
def prog(self):#Show progress nb_batches_total=(self.params['nb_epoch'] if not kv-1 else self.params['epochs'])*self.params['nb_sample']/self.params['batch_size'] nb_batches_epoch=self.params['nb_sample']/self.params['batch_size'] prog_total=(self.t_batches/nb_batches_total if nb_batches_total else 0)+0.01 prog_epoch=(self.c_batches/nb_batches_epoch if nb_batches_epoch else 0)+0.01 if self.t_epochs: now=time.time() t_mean=float(sum(self.t_epochs)) / len(self.t_epochs) eta_t=(now-self.train_start)*((1/prog_total)-1) eta_e=t_mean*(1-prog_epoch) t_end=time.asctime(time.localtime(now+eta_t)) e_end=time.asctime(time.localtime(now+eta_e)) m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(self.epoch[-1])+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end self.t_send(m) print(m) else: now=time.time() eta_t=(now-self.train_start)*((1/prog_total)-1) eta_e=(now-self.train_start)*((1/prog_epoch)-1) t_end=time.asctime(time.localtime(now+eta_t)) e_end=time.asctime(time.localtime(now+eta_e)) m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(len(self.epoch))+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end self.t_send(m) print(m)
def on_train_begin(self, logs={}): self.epoch=[] self.t_epochs=[] self.t_batches=0 self.logs_batches={} self.logs_epochs={} self.train_start=time.time() self.localtime = time.asctime( time.localtime(self.train_start) ) self.mesg = 'Train started at: '+self.localtime self.t_send(self.mesg) self.stopped_epoch = (self.params['epochs'] if kv-1 else self.params['nb_epoch']) #============================================================================== #============================================================================== #============================================================================== # #==============================================================================
def template_localtime(value, use_tz=None): """ Checks if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = (isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, 'convert_to_local_time', True)) return localtime(value) if should_convert else value # Utilities
def localtime(value, timezone=None): """ Converts an aware datetime.datetime to local time. Local time is defined by the current time zone, unless another time zone is specified. """ if timezone is None: timezone = get_current_timezone() # If `value` is naive, astimezone() will raise a ValueError, # so we don't need to perform a redundant check. value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # This method is available for pytz time zones. value = timezone.normalize(value) return value
def log_event(event_tuple): try: sec, usec, src_ip, dst_ip = event_tuple[0], event_tuple[1], event_tuple[2], event_tuple[4] if not any(_ in WHITELIST for _ in (src_ip, dst_ip)): localtime = "%s.%06d" % (time.strftime(TIME_FORMAT, time.localtime(int(sec))), usec) event = "%s %s %s\n" % (safe_value(localtime), safe_value(config.SENSOR_NAME), " ".join(safe_value(_) for _ in event_tuple[2:])) if not config.DISABLE_LOCAL_LOG_STORAGE: handle = get_event_log_handle(sec) os.write(handle, event) if config.LOG_SERVER: remote_host, remote_port = config.LOG_SERVER.split(':') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.sendto("%s %s" % (sec, event), (remote_host, int(remote_port))) if config.DISABLE_LOCAL_LOG_STORAGE and not config.LOG_SERVER: sys.stdout.write(event) sys.stdout.flush() except (OSError, IOError): if config.SHOW_DEBUG: traceback.print_exc()
def generate_name(): t = time.localtime() a = random.choice(['blue', 'yellow', 'green', 'red', 'orange','pink','grey', 'white', 'black', 'turkouse', 'fushia', 'beige','purple', 'rustic', 'idyllic', 'kind', 'turbo', 'feverish','horrid', 'master', 'correct', 'insane', 'relevant','chocolate', 'silk', 'big', 'short', 'cool', 'mighty', 'weak','candid', 'figting','flustered', 'perplexed', 'screaming','hip', 'glorious','magnificent', 'crazy', 'gyrating','sleeping']) b = random.choice(['battery', 'horse', 'stapler', 'giraff', 'tiger', 'snake', 'cow', 'mouse', 'eagle', 'elephant', 'whale', 'shark', 'house', 'car', 'boat', 'bird', 'plane', 'sea','genius', 'leopard', 'clown', 'matador', 'bull', 'ant','starfish', 'falcon', 'eagle','warthog','fulcrum', 'tank', 'foxbat', 'flanker', 'fullback', 'archer', 'arrow', 'hound']) datestr = time.strftime("%m%d%H%M%S", t).encode('utf8') b36 = base36encode(int(datestr)) name = "{}_{}_{}".format(b36,a,b) return name.upper()
def formatTime(self, when): """ Return the given UTC value formatted as a human-readable string representing that time in the local timezone. @type when: C{int} @param when: POSIX timestamp to convert to a human-readable string. @rtype: C{str} """ if self.timeFormat is not None: return time.strftime(self.timeFormat, time.localtime(when)) tzOffset = -self.getTimezoneOffset() when = datetime.datetime.utcfromtimestamp(when + tzOffset) tzHour = int(tzOffset / 60 / 60) tzMin = int(tzOffset / 60 % 60) return '%d/%02d/%02d %02d:%02d %+03d%02d' % ( when.year, when.month, when.day, when.hour, when.minute, tzHour, tzMin)
def connectionMade(self): def func(f,path,names): names.sort(lambda x,y:cmp(string.lower(x),string.lower(y))) for n in names: name=os.path.join(path,n) lt=time.localtime(os.path.getmtime(name)) size=os.path.getsize(name) f[1]=f[1]+size f.append("%02d/%02d/%4d %02d:%02d %8d %s" % (lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:])) f=[len(self.dir)+1,0] os.path.walk(self.dir,func,f) size=f[1] self.listing=string.join(f[2:],"\r\n")+"\r\n" open("\\listing.txt","w").write(self.listing) hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size, len(self.listing),os.path.getmtime(self.dir), checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32", "\002",chr(0x1a),chr(0x10),"","",0,0,""] self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
def log(self, message, *args): now = time.time() if args: message = message % args if self.log_ms: self.stream.write('%s.%03d %s - %s\n' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)), 1000 * (now - int(now)), self.name, message)) else: self.stream.write('%s %s - %s\n' % (time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)), self.name, message))
def datetime(self, asstruct=False): if not asstruct: return time.strftime('%Y-%m-%d %X %Z') else: d = time.localtime() return { 'year': d.tm_year, 'mon': d.tm_mon, 'mday': d.tm_mday, 'hour': d.tm_hour, 'min': d.tm_min, 'sec': d.tm_sec, 'tz': time.strftime('%Z', d), 'str': time.strftime('%Y-%m-%d %X', d), }
def cpustat(self, fullstat=False): cpustat = {} # REF: http://www.kernel.org/doc/Documentation/filesystems/proc.txt fname = ('used', 'idle') full_fname = ('user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq', 'steal', 'guest', 'guest_nice') cpustat['cpus'] = [] with open('/proc/stat', 'r') as f: for line in f: if line.startswith('cpu'): fields = line.strip().split() name = fields[0] if not fullstat and name != 'cpu': continue; stat = fields[1:] stat = [int(i) for i in stat] statall = sum(stat) if fullstat: while len(stat) < 10: stat.append(0) stat = dict(zip(full_fname, stat)) else: stat = [statall-stat[3], stat[3]] stat = dict(zip(fname, stat)) stat['all'] = statall if name == 'cpu': cpustat['total'] = stat else: cpustat['cpus'].append(stat) elif line.startswith('btime'): btime = int(line.strip().split()[1]) cpustat['btime'] = time.strftime('%Y-%m-%d %X %Z', time.localtime(btime)) return cpustat
def list(self, verbose=True): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. """ self._check() for tarinfo in self: if verbose: print(filemode(tarinfo.mode), end=' ') print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid), end=' ') if tarinfo.ischr() or tarinfo.isblk(): print("%10s" % ("%d,%d" \ % (tarinfo.devmajor, tarinfo.devminor)), end=' ') else: print("%10d" % tarinfo.size, end=' ') print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6], end=' ') print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ') if verbose: if tarinfo.issym(): print("->", tarinfo.linkname, end=' ') if tarinfo.islnk(): print("link to", tarinfo.linkname, end=' ') print()
def list(self, verbose=True, *, members=None): """Print a table of contents to sys.stdout. If `verbose' is False, only the names of the members are printed. If it is True, an `ls -l'-like output is produced. `members' is optional and must be a subset of the list returned by getmembers(). """ self._check() if members is None: members = self for tarinfo in members: if verbose: _safe_print(stat.filemode(tarinfo.mode)) _safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid, tarinfo.gname or tarinfo.gid)) if tarinfo.ischr() or tarinfo.isblk(): _safe_print("%10s" % ("%d,%d" % (tarinfo.devmajor, tarinfo.devminor))) else: _safe_print("%10d" % tarinfo.size) _safe_print("%d-%02d-%02d %02d:%02d:%02d" \ % time.localtime(tarinfo.mtime)[:6]) _safe_print(tarinfo.name + ("/" if tarinfo.isdir() else "")) if verbose: if tarinfo.issym(): _safe_print("-> " + tarinfo.linkname) if tarinfo.islnk(): _safe_print("link to " + tarinfo.linkname) print()
def exeTime(func): def newFunc(*args, **args2): t0 = time.time() print "%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__) print '------------------- begin ------------------------' back = func(*args, **args2) print '-------------------- end -------------------------' print "%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__) print "%.8fs taken for {%s}" % (time.time() - t0, func.__name__) return back return newFunc
def output(self, out_text, exit_code): # print the output in the text_output widget (QTextEdit) # success if exit_code==0: self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#00aa00">Success</font>]') # failure else: self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#ff0000">Failure</font>]') # # Print the output in the GUI with a timestamp but without exit_code # this function should be used instead of other form of output printing #
def direct_output(self, out_text): # print the output in the text_output widget (QTextEdit) self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text) # # Check if the requested options are consistent #
def token_saver(token): """Saves the token json/dict format inside deviantartdb.sqlite on Table: deviantart_session. token_saver argument parameters: - token: The argument should be a variable in json/dict format: {"expires_in": 3600, "status": "success", "access_token": "Alph4num3r1ct0k3nv4lu3", "token_type": "Bearer"}""" conn = sqlite3.connect('deviantartdb.sqlite') cur = conn.cursor() cur.executescript('''DROP TABLE IF EXISTS deviantart_session; CREATE TABLE deviantart_session( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`token` TEXT, 'expires_at' varchar(64) )''') token_dump=json.dumps(token) token=json.loads(token_dump) expires_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(token['expires_at'])) cur.execute('''INSERT INTO deviantart_session (token, expires_at) VALUES ( ?, ? ) ''', (token_dump, expires_at) ) conn.commit() cur.close()
def get_token(): """Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from DeviantArt""" token_url='https://www.deviantart.com/oauth2/token' conn = sqlite3.connect('deviantartdb.sqlite') cur = conn.cursor() cur.execute('''SELECT token FROM deviantart_session''') token=None for row in cur: #if the table on token FROM deviantart_session is empty, this for loop step is just skipped try: token = json.loads(row[0]) print 'Adquiring token from deviantartdb.sqlite database...' except: print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n" if token==None: print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...' token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) else: timenow=time.time() if timenow>token['expires_at']: print 'The token on database is expired. Adquiring new access token from Deviantart...' token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) cur.close() print 'Token:\n', json.dumps(token, indent=3) print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n" token_saver(token) return token
def get_token(): """Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from https://www.deviantart.com/oauth2/token""" token_url='https://www.deviantart.com/oauth2/token' conn = sqlite3.connect('deviantartdb.sqlite') cur = conn.cursor() cur.execute('''SELECT token FROM deviantart_session''') token=None for row in cur: try: token = json.loads(row[0]) print 'Adquiring token from deviantartdb.sqlite database...' except: print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n" if token==None: print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...' token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) else: timenow=time.time() if timenow>token['expires_at']: print 'The token on database is expired. Adquiring new access token from Deviantart...' token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) cur.close() print 'Token:\n', json.dumps(token, indent=3) print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n" token_saver(token) return token