Python time.asctime() Examples

The following are code examples for showing how to use time.asctime(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.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 2
Project: pyserverchan   Author: GanjinZero   File: watch_process.py    MIT License 6 votes vote down vote up
def single_watch():
    now_time = time.asctime(time.localtime(time.time()))
    result_python = watch_python()
    result_folder1 = watch_folder("~/user001/thuys/specter_fast/model/")
    result_word2vec = watch_folder("~/user001/thuys/embedding/word2vec/")
    result_glove = watch_folder("~/user001/thuys/embedding/glove/")
    result = os.linesep.join([now_time, result_python, result_folder1, result_word2vec, result_glove])
    result = result.replace(os.linesep, os.linesep + os.linesep)
    
    if result_python == "No python found!!!":
        result = result_python

    #print(result)
    svc = pyserver.ServerChan()
    svc.output_to_weixin(title='Jiangsu_GPU Server Python Process', content=result)
    
    if result == "No python found!!!":
        return 1
    return 0 
Example 3
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ec2_asg.py    MIT License 6 votes vote down vote up
def wait_for_term_inst(connection, term_instances):
    wait_timeout = module.params.get('wait_timeout')
    group_name = module.params.get('name')
    as_group = describe_autoscaling_groups(connection, group_name)[0]
    props = get_properties(as_group)
    count = 1
    wait_timeout = time.time() + wait_timeout
    while wait_timeout > time.time() and count > 0:
        module.debug("waiting for instances to terminate")
        count = 0
        as_group = describe_autoscaling_groups(connection, group_name)[0]
        props = get_properties(as_group)
        instance_facts = props['instance_facts']
        instances = (i for i in instance_facts if i in term_instances)
        for i in instances:
            lifecycle = instance_facts[i]['lifecycle_state']
            health = instance_facts[i]['health_status']
            module.debug("Instance %s has state of %s,%s" % (i, lifecycle, health))
            if lifecycle == 'Terminating' or health == 'Unhealthy':
                count += 1
        time.sleep(10)

    if wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(msg="Waited too long for old instances to terminate. %s" % time.asctime()) 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ec2_asg.py    MIT License 6 votes vote down vote up
def wait_for_new_inst(connection, group_name, wait_timeout, desired_size, prop):

    # make sure we have the latest stats after that last loop.
    as_group = describe_autoscaling_groups(connection, group_name)[0]
    props = get_properties(as_group)
    module.debug("Waiting for %s = %s, currently %s" % (prop, desired_size, props[prop]))
    # now we make sure that we have enough instances in a viable state
    wait_timeout = time.time() + wait_timeout
    while wait_timeout > time.time() and desired_size > props[prop]:
        module.debug("Waiting for %s = %s, currently %s" % (prop, desired_size, props[prop]))
        time.sleep(10)
        as_group = describe_autoscaling_groups(connection, group_name)[0]
        props = get_properties(as_group)
    if wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(msg="Waited too long for new instances to become viable. %s" % time.asctime())
    module.debug("Reached %s: %s" % (prop, desired_size))
    return props 
Example 5
Project: steamlink   Author: steamlink   File: steamlink.py    MIT License 6 votes vote down vote up
def save(self, withvirtual=False):
		r = {}
		r['steam_id'] = self.steam_id
		r['name'] = self.name
		r['desc'] = self.desc
		if withvirtual:
			r['Name'] = self.name
			r['Description'] = self.desc
			r['Meshes'] = len(Mesh._table)
			r['Time'] = time.asctime()
			r['Load'] = "%3.1f%%" % self.cpubusy
			r['Mesh records'] = len(Mesh._table)
			r['Node records'] = len(Node._table)
			r['Packet records'] = len(Packet._table)
		return r


#
# Mesh
# 
Example 6
Project: gradefast   Author: jhartz   File: local.py    MIT License 6 votes vote down vote up
def provide_output_log(self, settings: Settings) -> iochannels.Log:
        if not settings.log_file:
            return iochannels.NullLog()

        file = open(settings.log_file.get_local_path(), "a", encoding="utf8")
        if settings.log_as_html:
            file.write("<h1>\n")
        else:
            file.write("=" * 79 + "\n")
        file.write("GradeFast Log -- ")
        file.write(time.asctime())
        file.write("\n")
        if settings.log_as_html:
            file.write("</h1>\n")
            return iochannels.HTMLFileLog(file)
        else:
            file.write("=" * 79 + "\n")
            return iochannels.FileLog(file) 
Example 7
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_from(self, from_, time_=None):
        """Set "From " line, formatting and appending time_ if specified."""
        if time_ is not None:
            if time_ is True:
                time_ = time.gmtime()
            from_ += ' ' + time.asctime(time_)
        self._from = from_ 
Example 8
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_conversions(self):
        self.assertTrue(time.ctime(self.t)
                     == time.asctime(time.localtime(self.t)))
        self.assertTrue(long(time.mktime(time.localtime(self.t)))
                     == long(self.t)) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_asctime(self):
        time.asctime(time.gmtime(self.t))
        self.assertRaises(TypeError, time.asctime, 0)
        self.assertRaises(TypeError, time.asctime, ())
        # XXX: Posix compiant asctime should refuse to convert
        # year > 9999, but Linux implementation does not.
        # self.assertRaises(ValueError, time.asctime,
        #                  (12345, 1, 0, 0, 0, 0, 0, 0, 0))
        # XXX: For now, just make sure we don't have a crash:
        try:
            time.asctime((12345, 1, 1, 0, 0, 0, 0, 1, 0))
        except ValueError:
            pass 
Example 10
Project: mmdetection   Author: open-mmlab   File: setup.py    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 11
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    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 12
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ec2_asg.py    MIT License 5 votes vote down vote up
def elb_dreg(asg_connection, group_name, instance_id):
    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
    as_group = describe_autoscaling_groups(asg_connection, group_name)[0]
    wait_timeout = module.params.get('wait_timeout')
    count = 1
    if as_group['LoadBalancerNames'] and as_group['HealthCheckType'] == 'ELB':
        elb_connection = boto3_conn(module,
                                    conn_type='client',
                                    resource='elb',
                                    region=region,
                                    endpoint=ec2_url,
                                    **aws_connect_params)
    else:
        return

    for lb in as_group['LoadBalancerNames']:
        deregister_lb_instances(elb_connection, lb, instance_id)
        module.debug("De-registering %s from ELB %s" % (instance_id, lb))

    wait_timeout = time.time() + wait_timeout
    while wait_timeout > time.time() and count > 0:
        count = 0
        for lb in as_group['LoadBalancerNames']:
            lb_instances = describe_instance_health(elb_connection, lb, [])
            for i in lb_instances['InstanceStates']:
                if i['InstanceId'] == instance_id and i['State'] == "InService":
                    count += 1
                    module.debug("%s: %s, %s" % (i['InstanceId'], i['State'], i['Description']))
        time.sleep(10)

    if wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(msg="Waited too long for instance to deregister. {0}".format(time.asctime())) 
Example 13
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ec2_asg.py    MIT License 5 votes vote down vote up
def wait_for_elb(asg_connection, group_name):
    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
    wait_timeout = module.params.get('wait_timeout')

    # if the health_check_type is ELB, we want to query the ELBs directly for instance
    # status as to avoid health_check_grace period that is awarded to ASG instances
    as_group = describe_autoscaling_groups(asg_connection, group_name)[0]

    if as_group.get('LoadBalancerNames') and as_group.get('HealthCheckType') == 'ELB':
        module.debug("Waiting for ELB to consider instances healthy.")
        elb_connection = boto3_conn(module,
                                    conn_type='client',
                                    resource='elb',
                                    region=region,
                                    endpoint=ec2_url,
                                    **aws_connect_params)

        wait_timeout = time.time() + wait_timeout
        healthy_instances = elb_healthy(asg_connection, elb_connection, group_name)

        while healthy_instances < as_group.get('MinSize') and wait_timeout > time.time():
            healthy_instances = elb_healthy(asg_connection, elb_connection, group_name)
            module.debug("ELB thinks %s instances are healthy." % healthy_instances)
            time.sleep(10)
        if wait_timeout <= time.time():
            # waiting took too long
            module.fail_json(msg="Waited too long for ELB instances to be healthy. %s" % time.asctime())
        module.debug("Waiting complete. ELB thinks %s instances are healthy." % healthy_instances) 
Example 14
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ec2_asg.py    MIT License 5 votes vote down vote up
def wait_for_target_group(asg_connection, group_name):
    region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
    wait_timeout = module.params.get('wait_timeout')

    # if the health_check_type is ELB, we want to query the ELBs directly for instance
    # status as to avoid health_check_grace period that is awarded to ASG instances
    as_group = describe_autoscaling_groups(asg_connection, group_name)[0]

    if as_group.get('TargetGroupARNs') and as_group.get('HealthCheckType') == 'ELB':
        module.debug("Waiting for Target Group to consider instances healthy.")
        elbv2_connection = boto3_conn(module,
                                      conn_type='client',
                                      resource='elbv2',
                                      region=region,
                                      endpoint=ec2_url,
                                      **aws_connect_params)

        wait_timeout = time.time() + wait_timeout
        healthy_instances = tg_healthy(asg_connection, elbv2_connection, group_name)

        while healthy_instances < as_group.get('MinSize') and wait_timeout > time.time():
            healthy_instances = tg_healthy(asg_connection, elbv2_connection, group_name)
            module.debug("Target Group thinks %s instances are healthy." % healthy_instances)
            time.sleep(10)
        if wait_timeout <= time.time():
            # waiting took too long
            module.fail_json(msg="Waited too long for ELB instances to be healthy. %s" % time.asctime())
        module.debug("Waiting complete. Target Group thinks %s instances are healthy." % healthy_instances) 
Example 15
Project: spqrel_tools   Author: LCAS   File: Kernel.py    MIT License 5 votes vote down vote up
def _processDate(self, elem, sessionID):
        """Process a <date> AIML element.

        <date> elements resolve to the current date and time.  The
        AIML specification doesn't require any particular format for
        this information, so I go with whatever's simplest.

        """
        return time.asctime()

    # <formal> 
Example 16
Project: relay-bench   Author: uwsampl   File: dashboard.py    Apache License 2.0 5 votes vote down vote up
def run_experiment(info, experiments_dir, tmp_data_dir, exp_name):

    to_local_time = lambda sec: time.asctime(time.localtime(sec))
    exp_dir = os.path.join(experiments_dir, exp_name)
    exp_conf = info.exp_config_dir(exp_name)

    # set up a temporary data directory for that experiment
    exp_data_dir = os.path.join(tmp_data_dir, exp_name)
    idemp_mkdir(exp_data_dir)

    # Mark the start and the end of an experiment
    start_time = time.time()
    start_msg = f'Experiment {exp_name} starts @ {to_local_time(start_time)}'
    print_log(start_msg)
    # run the run.sh file on the configs directory and the destination directory
    subprocess.call([os.path.join(exp_dir, 'run.sh'), exp_conf, exp_data_dir],
                    cwd=exp_dir)
    end_time = time.time()
    delta = datetime.timedelta(seconds=end_time - start_time)
    # collect the status file from the destination directory, copy to status dir
    status = validate_status(exp_data_dir)
    # show experiment status to terminal
    if status['success']:
        end_msg = f'Experiment {exp_name} ends @ {to_local_time(end_time)}\nTime Delta: {delta}'
        print_log(end_msg)
    else:
        print_log(f'*** {exp_name} FAILED ***\n*** Reason: {status["message"]} ***')
    # record start & end & duration of an experiment
    status['start_time'] = to_local_time(start_time)
    status['end_time'] = to_local_time(end_time)
    status['time_delta'] = str(delta)
    # not literally copying because validate may have produced a status that generated an error
    info.report_exp_status(exp_name, 'run', status)
    return status['success'] 
Example 17
Project: Kaggler   Author: jeongyoonlee   File: data_io.py    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 18
Project: SublimeKSP   Author: nojanath   File: ksp_compiler.py    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
        localtime = time.asctime( time.localtime(time.time()) )
        self.compiled_code = "{ Compiled on " + localtime + " }\n" + self.compiled_code 
Example 19
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getLogHeader():
	#WRITE INFO
	user = getUsername()
	host = getHostname()
	logheader = "[ "+user+"@"+host+": "+time.asctime()+" ]\n"
	return logheader

#===================== 
Example 20
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def closeFunctionLog(functionname=None, logfile=None, msg=True, stats=None):
	"""
	Used by appionLoop
	"""
	if logfile is not None:
		pass
	elif functionname is not None:
		logfile = functionname+".log"
	else:
		logfile = "function.log"
	if msg is True:
		apDisplay.printMsg("Closing out function log: "+logfile)
	if stats is not None and stats['count'] > 3:
		timesum = stats['timesum']
		timesumsq = stats['timesumsq']
		count = stats['count']
		timeavg = float(timesum)/float(count)
		timestdev = math.sqrt(float(count*timesumsq - timesum**2) / float(count*(count-1)))
		avgtimestr = "average time: "+apDisplay.timeString(timeavg,timestdev)+"\n"
	else:
		avgtimestr = ""

	#WRITE INFO
	timestamp = "["+time.asctime()+"]\n"
	out="finished run"
	if functionname is not None:
		out += " of "+functionname
	out += "\n"
	f=open(logfile,'a')
	f.write(timestamp)
	f.write(avgtimestr)
	f.write(out)
	f.close()

#===================== 
Example 21
Project: Old-school-processing   Author: cianfrocco-lab   File: tiltfile.py    MIT License 5 votes vote down vote up
def saveData(savedata, filename, filetype=None):
	"""
	savedata = {}
	savedata['theta'] = self.data['theta']
	savedata['gamma'] = self.data['gamma']
	savedata['phi'] = self.data['phi']
	savedata['savetime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['filetype'] = tiltfile.filetypes[self.data['filetypeindex']]
	savedata['picks1'] = self.getArray1()
	savedata['picks2'] = self.getArray2()
	savedata['align1'] = self.getAlignedArray1()
	savedata['align2'] = self.getAlignedArray2()
	savedata['rmsd'] = self.getRmsdArray()
	savedata['image1name'] = self.panel1.filename
	savedata['image2name'] = self.panel2.filename
	"""

	if filetype is None:
		filetype = guessFileType(filename)

	savedata['savetime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['filetype'] = filetype
	savedata['filename'] = os.path.basename(filename)

	if filetype == 'text':
		saveToTextFile(savedata, filename)
	elif filetype == 'xml':
		saveToXMLFile(savedata, filename)
	elif filetype == 'spider':
		saveToSpiderFile(savedata, filename)
	elif filetype == 'pickle':
		saveToPickleFile(savedata, filename)
	elif filetype == 'box':
		saveToBoxFile(savedata, filename)
	else:
		return False
		apDisplay.printWarning("unknown file type")

#--------------------------------------- 
Example 22
Project: resticprofile   Author: creativeprojects   File: console.py    GNU General Public License v3.0 5 votes vote down vote up
def _msg(self, message, ansi=None):
        '''
        Low level display message
        '''
        timed_message = time.asctime() + ' ' + message
        if ansi:
            print(ansi + timed_message)
        else:
            print(timed_message) 
Example 23
Project: ns3   Author: KyleBenson   File: rad_util.py    GNU General Public License v2.0 5 votes vote down vote up
def timestamp():
    """Return string containing current time stamp.

    Note: In Python 2 onwards can use time.asctime() with no arguments.

    """

    return time.asctime() 
Example 24
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: Utils.py    GNU General Public License v3.0 5 votes vote down vote up
def setup_logger(logger_name, log_file,key=str(), level=logging.INFO):
    global loggers
    if loggers.get(logger_name):
        return loggers.get(logger_name)
    else:
        logger = logging.getLogger(logger_name)
        logger.propagate = False
        formatter = logging.Formatter('SessionID[{}] %(asctime)s : %(message)s'.format(key))
        fileHandler = logging.FileHandler(log_file, mode='a')
        fileHandler.setFormatter(formatter)
        logger.setLevel(logging.INFO)
        logger.addHandler(fileHandler)
    return logger 
Example 25
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: threads.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        self.process = Popen(self.args,
        stdout=PIPE,stderr=STDOUT,preexec_fn=setsid)
        print '[New Thread {} ({})]'.format(self.process.pid,self.objectName())
        setup_logger('dhcp', './Logs/AccessPoint/dhcp.log',self.session)
        loggerDhcp = logging.getLogger('dhcp')
        loggerDhcp.info('---[ Start DHCP '+asctime()+']---')
        for line,data in enumerate(iter(self.process.stdout.readline, b'')):
            if 'DHCPREQUEST for' in data.rstrip():
                self.sendRequest.emit(data.split())
            elif 'DHCPACK on' in data.rstrip():
                self.sendRequest.emit(data.split())
            loggerDhcp.info(data.rstrip()) 
Example 26
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: dnsspoofNF.py    GNU General Public License v3.0 5 votes vote down vote up
def logggingCreate(self):
        setup_logger('dnsspoofAP', './Logs/AccessPoint/DnsSpoofModuleReq.log')
        self.logDNS = logging.getLogger('dnsspoofAP')
        self.logDNS.info('Dns Spoof: running... at: {}'.format(asctime())) 
Example 27
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: net-creds.py    GNU General Public License v3.0 5 votes vote down vote up
def setup_logger(logger_name, log_file,key, level=logging.INFO):
    l = logging.getLogger(logger_name)
    if 'credentials' in logger_name:
        formatter = logging.Formatter('SessionID[{}] %(asctime)s :[creds] %(message)s'.format(key),datefmt='%Y-%m-%d %H:%M:%S')
    elif 'netcreds' in logger_name:
        formatter = logging.Formatter('SessionID[{}] %(asctime)s :[url] %(message)s'.format(key),datefmt='%Y-%m-%d %H:%M:%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 28
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: bdf_proxy.py    GNU General Public License v3.0 5 votes vote down vote up
def setup_logger(logger_name, log_file,key, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('SessionID[{}] %(asctime)s : %(message)s'.format(key))
    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 29
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: build.py    GNU General Public License v3.0 5 votes vote down vote up
def main( argv=None ):
	if not argv:
		argv = sys.argv
	try:
		if len( argv ) == 1:
			print "Usage: build.py [clean|all|<name>]"
		else:
			print "# Built on %s\n" % (  time.asctime( time.localtime() ) )
			if argv[1] == "clean":
				clean()
			elif argv[1] == "all":
				for root, dirs, files in os.walk( "./src/egghunter/" ):
					for name in files:
						build( name[:-4] )
				for root, dirs, files in os.walk( "./src/migrate/" ):
					for name in files:
						build( name[:-4] )
				for root, dirs, files in os.walk( "./src/single/" ):
					for name in files:
						build( name[:-4] )
				for root, dirs, files in os.walk( "./src/stage/" ):
					for name in files:
						build( name[:-4] )
				for root, dirs, files in os.walk( "./src/stager/" ):
					for name in files:
						build( name[:-4] )
				for root, dirs, files in os.walk( "./src/kernel/" ):
					for name in files:
						build( name[:-4] )
			else:
				build( argv[1] )
	except Exception, e:
		print "[-] ", e
#=============================================================================# 
Example 30
Project: LaserTOF   Author: kyleuckert   File: mio5.py    MIT License 5 votes vote down vote up
def write_file_header(self):
        # write header
        hdr = np.zeros((), NDT_FILE_HDR)
        hdr['description'] = 'MATLAB 5.0 MAT-file Platform: %s, Created on: %s' \
            % (os.name,time.asctime())
        hdr['version'] = 0x0100
        hdr['endian_test'] = np.ndarray(shape=(),
                                      dtype='S2',
                                      buffer=np.uint16(0x4d49))
        self.file_stream.write(hdr.tostring()) 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: mailbox.py    GNU General Public License v3.0 5 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):
            message = self._string_to_bytes(message)
        if isinstance(message, bytes) and message.startswith(b'From '):
            newline = message.find(b'\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = b''
        elif isinstance(message, _mboxMMDFMessage):
            author = message.get_from().encode('ascii')
            from_line = b'From ' + author
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
            if from_line is not None:
                from_line = from_line.encode('ascii')
        if from_line is None:
            from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
        start = self._file.tell()
        self._file.write(from_line + linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: mailbox.py    GNU General Public License v3.0 5 votes vote down vote up
def set_from(self, from_, time_=None):
        """Set "From " line, formatting and appending time_ if specified."""
        if time_ is not None:
            if time_ is True:
                time_ = time.gmtime()
            from_ += ' ' + time.asctime(time_)
        self._from = from_ 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def test_conversions(self):
        self.assertEqual(time.ctime(self.t),
                         time.asctime(time.localtime(self.t)))
        self.assertEqual(int(time.mktime(time.localtime(self.t))),
                         int(self.t)) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def test_asctime(self):
        time.asctime(time.gmtime(self.t))

        # Max year is only limited by the size of C int.
        for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
            asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
            self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
        self.assertRaises(OverflowError, time.asctime,
                          (TIME_MAXYEAR + 1,) + (0,) * 8)
        self.assertRaises(OverflowError, time.asctime,
                          (TIME_MINYEAR - 1,) + (0,) * 8)
        self.assertRaises(TypeError, time.asctime, 0)
        self.assertRaises(TypeError, time.asctime, ())
        self.assertRaises(TypeError, time.asctime, (0,) * 10) 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def yearstr(self, y):
        return time.asctime((y,) + (0,) * 8).split()[-1] 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: test_mailbox.py    GNU General Public License v3.0 5 votes vote down vote up
def test_maildir_to_mboxmmdf(self):
        # Convert MaildirMessage to mboxmessage and MMDFMessage
        pairs = (('D', ''), ('F', 'F'), ('P', ''), ('R', 'A'), ('S', 'R'),
                 ('T', 'D'), ('DFPRST', 'RDFA'))
        for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
            msg_maildir = mailbox.MaildirMessage(_sample_message)
            msg_maildir.set_date(0.0)
            for setting, result in pairs:
                msg_maildir.set_flags(setting)
                msg = class_(msg_maildir)
                self.assertEqual(msg.get_flags(), result)
                self.assertEqual(msg.get_from(), 'MAILER-DAEMON %s' %
                             time.asctime(time.gmtime(0.0)))
            msg_maildir.set_subdir('cur')
            self.assertEqual(class_(msg_maildir).get_flags(), 'RODFA') 
Example 37
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: Main.py    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 38
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    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 39
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    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 40
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: utils.py    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 41
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: NetCreds.py    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 42
Project: ns3   Author: bvamanan   File: rad_util.py    GNU General Public License v2.0 5 votes vote down vote up
def timestamp():
    """Return string containing current time stamp.

    Note: In Python 2 onwards can use time.asctime() with no arguments.

    """

    return time.asctime() 
Example 43
Project: DDEA-DEV   Author: TinyOS-Camp   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def ServeGUI(Function = None,
             HandlerClass = RequestHandler,
             ServerClass = BaseHTTPServer.HTTPServer,
             protocol="HTTP/1.0",
             port=HTTP_PORT):

    global DDEA_FUNC, BASE_SERVER_URL, ANAL_ROUTES
    from printhook import PrintHook

    DDEA_FUNC = Function

    StartLogger(int(port) + 1)

    phOut = PrintHook()
    phOut.Start(PRINT_LOG)

    server_address = ('', port)
    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()

    print time.asctime(), "Start serving HTTP on", sa[0], "port", sa[1]
    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        httpd.server_close()
        StopLogger()
        phOut.Stop()
        print time.asctime(), "Stop serving HTTP on", sa[0], "port", sa[1]
        exit(0) 
Example 44
Project: DDEA-DEV   Author: TinyOS-Camp   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def ServeGUI(ddea_main = None,
             spark_context = None,
             HandlerClass = RequestHandler,
             ServerClass = BaseHTTPServer.HTTPServer,
             protocol="HTTP/1.0",
             port=HTTP_PORT):

    global DDEA_FUNC, BASE_SERVER_URL, ANAL_ROUTES
    from printhook import PrintHook

    DDEA_FUNC = ddea_main

    StartLogger(int(port) + 1)

    phOut = PrintHook()
    phOut.Start(PRINT_LOG)

    server_address = ('', port)
    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()

    print time.asctime(), "Start serving HTTP on", sa[0], "port", sa[1]
    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        try:
            httpd.server_close()
            StopLogger()
            phOut.Stop()
            spark_context.stop()
        except:
            import traceback;print traceback.print_exc()
        finally:
            print time.asctime(), "Stop serving HTTP on", sa[0], "port", sa[1]
            exit(0) 
Example 45
Project: DDEA-DEV   Author: TinyOS-Camp   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def ServeGUI(Function = None,
             HandlerClass = RequestHandler,
             ServerClass = BaseHTTPServer.HTTPServer,
             protocol="HTTP/1.0",
             port=HTTP_PORT):

    global DDEA_FUNC, BASE_SERVER_URL, ANAL_ROUTES
    from printhook import PrintHook

    DDEA_FUNC = Function

    StartLogger(int(port) + 1)

    phOut = PrintHook()
    phOut.Start(PRINT_LOG)

    server_address = ('', port)
    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()

    print time.asctime(), "Start serving HTTP on", sa[0], "port", sa[1]
    try:
        httpd.serve_forever()
    except (KeyboardInterrupt, SystemExit):
        httpd.server_close()
        StopLogger()
        phOut.Stop()
        print time.asctime(), "Stop serving HTTP on", sa[0], "port", sa[1]
        exit(0) 
Example 46
Project: mptcp_with_machine_learning   Author: JamesRaynor67   File: rad_util.py    GNU General Public License v2.0 5 votes vote down vote up
def timestamp():
    """Return string containing current time stamp.

    Note: In Python 2 onwards can use time.asctime() with no arguments.

    """

    return time.asctime() 
Example 47
Project: CNKI-download   Author: CyrusRenty   File: main.py    MIT License 5 votes vote down vote up
def search_reference(self, ueser_input):
        '''
        第一次发送post请求
        再一次发送get请求,这次请求没有写文献等东西
        两次请求来获得文献列表
        '''
        static_post_data = {
            'action': '',
            'NaviCode': '*',
            'ua': '1.21',
            'isinEn': '1',
            'PageName': 'ASP.brief_default_result_aspx',
            'DbPrefix': 'SCDB',
            'DbCatalog': '中国学术期刊网络出版总库',
            'ConfigFile': 'CJFQ.xml',
            'db_opt': 'CJFQ,CDFD,CMFD,CPFD,IPFD,CCND,CCJD',  # 搜索类别(CNKI右侧的)
            'db_value': '中国学术期刊网络出版总库',
            'year_type': 'echar',
            'his': '0',
            'db_cjfqview': '中国学术期刊网络出版总库,WWJD',
            'db_cflqview': '中国学术期刊网络出版总库',
            '__': time.asctime(time.localtime()) + ' GMT+0800 (中国标准时间)'
        }
        # 将固定字段与自定义字段组合
        post_data = {**static_post_data, **ueser_input}
        # 必须有第一次请求,否则会提示服务器没有用户
        first_post_res = self.session.post(
            SEARCH_HANDLE_URL, data=post_data, headers=HEADER)
        # get请求中需要传入第一个检索条件的值
        key_value = quote(ueser_input.get('txt_1_value1'))
        self.get_result_url = GET_PAGE_URL + first_post_res.text + '&t=1544249384932&keyValue=' + key_value + '&S=1&sorttype='
        # 检索结果的第一个页面
        second_get_res = self.session.get(self.get_result_url, headers=HEADER)
        change_page_pattern_compile = re.compile(
            r'.*?pagerTitleCell.*?<a href="(.*?)".*')
        self.change_page_url = re.search(change_page_pattern_compile,
                                         second_get_res.text).group(1)
        self.parse_page(
            self.pre_parse_page(second_get_res.text), second_get_res.text) 
Example 48
Project: flask-monitor   Author: fraoustin   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def _dict(self):
        mydict = {}
        # manage timing
        mydict['timing'] = {}
        mydict['timing']['delta'] = self.timing
        mydict['timing']['start'] = self.request._stats_start_event
        mydict['timing']['asctime'] = asctime(gmtime(self.request._stats_start_event))
        # manage flask
        mydict['flask'] = {}
        mydict['flask']['secret_key'] = current_app.config['SECRET_KEY']
        mydict['flask']['server_name'] = current_app.config['SERVER_NAME']
        mydict['flask']['session_cookie_name'] = current_app.config['SESSION_COOKIE_NAME']
        mydict['flask']['session_cookie_domain'] = current_app.config['SESSION_COOKIE_DOMAIN']
        mydict['flask']['session_cookie_path'] = current_app.config['SESSION_COOKIE_PATH']
        mydict['flask']['session_cookie_httponly'] = current_app.config['SESSION_COOKIE_HTTPONLY']
        mydict['flask']['session_cookie_secure'] = current_app.config['SESSION_COOKIE_SECURE']
        mydict['flask']['session_refresh_each_request'] = current_app.config['SESSION_REFRESH_EACH_REQUEST']
        # manage request
        mydict['request'] = {}
        mydict['request']['url'] = request.url
        mydict['request']['args'] = {arg: request.args.get(arg) for arg in request.args}
        mydict['request']['view_args'] = request.view_args
        mydict['request']['path'] = request.path
        mydict['request']['method'] = request.method
        mydict['request']['remote_addr'] = request.remote_addr
        try:
            mydict['request']['rule'] = request.url_rule.rule
        except:
            mydict['request']['rule'] = ''
        #manage response
        mydict['response'] = {}
        mydict['response']['status_code'] = self.response.status_code
        mydict['response']['headers'] = { i:j for i,j in self.response.headers}
        return mydict 
Example 49
Project: AlleleHMM   Author: Danko-Lab   File: SQDedDriver.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setupLogging(logLevel, logFile):
    logging.basicConfig(level=logLevel,
                        filename=logFile,
                        filemode='w',
                        format='%(asctime)s.%(msecs)03d %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
                                           
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter=logging.Formatter('%(levelname)s %(asctime)s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console) 
Example 50
Project: AlleleHMM   Author: Danko-Lab   File: SQDedDriver.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setupLogging(logLevel, logFile):
    logging.basicConfig(level=logLevel,
                        filename=logFile,
                        filemode='w',
                        format='%(asctime)s.%(msecs)03d %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
                                           
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter=logging.Formatter('%(levelname)s %(asctime)s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)