本文整理汇总了Python中time.asctime函数的典型用法代码示例。如果您正苦于以下问题:Python asctime函数的具体用法?Python asctime怎么用?Python asctime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了asctime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DISPLAY_temp
def DISPLAY_temp(self):
""" Here be the first time we actually do some stuff from the internet!
"""
res, color = [], []
text = "Current temperature:"
res.append("{}{:>5}".format(
text, self.return_term('temp_in_fahr')))
color.append("{}{}".format('0' * len(text), '6' * 5))
res.append("Wind: {}".format(self.return_term('wind_string')))
color.append('0' * len(res[1]))
res.append("Current time: {}".format(time.asctime()))
color.append('0' * len(res[2]))
res.append("")
color.append("")
res.append("{}".format(self.return_term('observation_time')))
color.append('0' * len(res[-1]))
txt1 = "Request time: "
tmp = time.asctime(time.localtime(self.last_query))
res.append("{}{}".format(txt1, tmp))
color.append("{}{}".format('0' * len(txt1), '4' * len(tmp)))
txt1, txt2 = "Connection is ", "seconds old"
tmp = int(time.time()) - self.last_query
res.append("{}{:<5}{}".format(txt1, tmp, txt2))
color.append("{}{}{}".format(
'0' * len(txt1), '6' * 5, '0' * len(txt2)))
res.append("time out length: {}".format(self.time_out))
color.append('2' * len(res[-1]))
return res, color
示例2: exec_file
def exec_file(script, test_name, result_query, test_detail, log_file):
start = time.asctime()
chmod = os.popen("chmod +x ./{0}".format(script)).read()
if ":sh" in chmod:
print "Failed to chmod\n"
stop = time.asctime()
test_result = "Fail"
test_logger(log_file, "Chmod", start, stop, test_result)
if ":sh" not in chmod:
print "Pass chmod {0}".format(test_name)
stop = time.asctime()
test_result = "Pass"
test_logger(log_file, "Chmod", start, stop, test_result)
cmd = os.popen("./{0}".format(script)).read()
if result_query not in cmd:
print "Failed {0}\n".format(test_name)
print "Test detail: \n" + test_detail + "\n"
print "Result: \n" + cmd + "\n"
stop = time.asctime()
test_logger(log_file, test_name, start, stop, "Fail")
if result_query in cmd:
print "Pass {0}".format(test_name)
print "Test detail: \n" + test_detail + "\n"
print "Result: \n" + cmd + "\n"
stop = time.asctime()
test_logger(log_file, test_name, start, stop, "Pass")
示例3: submit_work
def submit_work(self, rpc, original_data, nonce_bin):
nonce_bin = bufreverse(nonce_bin)
nonce = nonce_bin.encode('hex')
solution = original_data[:152] + nonce + original_data[160:256]
param_arr = [ solution ]
result = rpc.getwork(param_arr)
print time.asctime(), "--> Upstream RPC result:", result
示例4: _render_increment_info
def _render_increment_info(increment):
"""Render increment information.
Args:
increment: Associated Increment.Increment instance.
Returns:
[['Content-Type', 'text/plain'], rendered_info]
"""
value = '\n'.join(('Manent backup increment.',
'',
'started: %(started_str)s (%(started)s)',
'finished: %(finished_str)s (%(finished)s)',
'fs: %(fs_digest)s:%(fs_level)s',
'hostname: %(hostname)s',
'backup: %(backup)s',
'comment: %(comment)s'))
started = increment.get_attribute('ctime')
finished = increment.get_attribute('ctime')
value %= {'started_str': time.asctime(time.localtime(float(started))),
'started': started,
'finished_str': time.asctime(time.localtime(float(finished))),
'finished': finished,
'fs_digest': base64.b64encode(
increment.get_attribute('fs_digest')),
'fs_level': increment.get_attribute('fs_level'),
'hostname': increment.get_attribute('hostname'),
'backup': increment.get_attribute('backup'),
'comment': increment.get_attribute('comment')}
return [['Content-Type', 'text/plain']], value
示例5: remote_exec_file
def remote_exec_file(script, host, port, user, password, test_name, result_query, test_detail, log_file):
start = time.asctime()
cl = paramiko.SSHClient()
cl.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
cc = cl.connect(host, port=port, username=user, password=password)
except paramiko.ssh_exception.AuthenticationException:
print "Auth Error"
except paramiko.ssh_exception.SSHException:
print "Protocol Error"
except paramiko.transport:
print "General Error"
except socket.error:
print "Socket Error"
scp = SCPClient(cl.get_transport())
scp.put(script,script)
cl.exec_command("chmod +x ./{0}".format(script))
stdin, stdout, stderr = cl.exec_command("./{0}".format(script))
a = stdout.readlines()
cmd = str(a)
if result_query not in cmd:
print "Failed {0}\n".format(test_name)
print "Test detail: \n" + test_detail + "\n"
print "Result: \n" + cmd + "\n"
stop = time.asctime()
test_logger(log_file, test_name, start, stop, "Fail")
if result_query in cmd:
print "Pass {0}".format(test_name)
print "Test detail: \n" + test_detail + "\n"
print "Result: \n" + cmd + "\n"
stop = time.asctime()
test_logger(log_file, test_name, start, stop, "Pass")
示例6: loadConfigFile
def loadConfigFile():
global CONFIG_FILE
global CONFIG_DIR
global DEFAULTS
filename = os.path.join(CONFIG_DIR, CONFIG_FILE)
if not os.path.exists(filename):
log ('Configuration file does not exist. Using defaults.')
return
fd = open(filename, 'r')
try:
for line in fd.readlines():
line = line.strip()
if line.startswith('#'):
continue
parts = line.split('=')
key = parts[0]
val = parts[1]
if DEFAULTS.has_key(key):
if isinstance(DEFAULTS[key],int):
DEFAULTS[key] = int(val)
else:
DEFAULTS[key] = val
else:
print time.asctime(),'Ignoring unknown config variable ' + key
finally:
fd.close()
示例7: _update_date
def _update_date(self, series):
_date_aired = series.episode(series.fileDetails.seasonNum, series.fileDetails.episodeNums)[0].first_aired
cur_date = time.localtime(os.path.getmtime(series.fileDetails.newName))
if _date_aired:
_date_aired = datetime.datetime.combine(_date_aired, datetime.time())
tt = _date_aired.timetuple()
log.debug('Current File Date: %s Air Date: %s' % (time.asctime(cur_date), time.asctime(tt)))
tup_cur = [cur_date[0],
cur_date[1],
cur_date[2],
cur_date[3],
cur_date[4],
cur_date[5],
cur_date[6],
cur_date[7],
-1]
tup = [tt[0], tt[1], tt[2], 20, 0, 0, tt[6], tt[7], tt[8]]
if tup != tup_cur:
time_epoc = time.mktime(tup)
try:
log.info("Updating First Aired: %s" % _date_aired)
os.utime(series.fileDetails.newName, (time_epoc, time_epoc))
except (OSError, IOError), exc:
log.error("Skipping, Unable to update time: %s" % series.fileDetails.newName)
log.error("Unexpected error: %s" % exc)
else:
log.info("First Aired Correct: %s" % _date_aired)
示例8: reserve_pieces
def reserve_pieces(self, pieces, sdownload, all_or_nothing = False):
pieces_to_send = []
ex = "None"
result = []
for piece in pieces:
if self.is_reserved(piece):
result.append(piece)
elif not self.is_ignored(piece):
pieces_to_send.append(piece)
if DEBUG:
print >> sys.stderr,time.asctime(),'-', "helper: reserve_pieces: result is",result,"to_send is",pieces_to_send
if pieces_to_send == []:
return result
if self.coordinator is not None:
if DEBUG:
print >>sys.stderr,time.asctime(),'-', "helper: reserve_pieces: I am coordinator, calling self.coordinator.reserve_pieces"
new_reserved_pieces = self.coordinator.network_reserve_pieces(pieces_to_send, all_or_nothing)
for piece in new_reserved_pieces:
self._reserve_piece(piece)
else:
if DEBUG:
print >>sys.stderr,time.asctime(),'-', "helper: reserve_pieces: sending remote reservation request"
self.send_or_queue_reservation(sdownload,pieces_to_send,result)
return []
result = []
for piece in pieces:
if self.is_reserved(piece):
result.append(piece)
else:
self._ignore_piece(piece)
return result
示例9: do_nothing
def do_nothing():
try:
import time
print time.asctime()
time.sleep(1)
except KeyboardInterrupt:
print "Aborted."
示例10: get_commits
def get_commits(repository, branch, page):
path = settings.REPOSITORY_PATH
if (path[len(path)-2] != '/'):
path += '/'
repo = git.Repo(path+repository)
commits = repo.commits(branch, max_count=10, skip=int(page)*10)
n_commits = len(commits)
resp_json = {"commits": n_commits}
next_page = True
end_pagination = repo.commits(branch, max_count=10, skip=int(page)*10+10)
if (end_pagination == []):
next_page = False
resp_json["next_page"] = next_page
i=0
while i < n_commits:
resp_json[str(i)]=[commits[i].id, # id del commit
commits[i].tree.id, # id del arbol asociado al commit
commits[i].author.name, # nombre del autor del codigo
commits[i].author.email, # email del autor del codigo
time.asctime(commits[i].authored_date), # fecha de creacion del codigo
commits[i].committer.name, # nombre del autor del commit
commits[i].committer.email, # email del autor del commit
time.asctime(commits[i].committed_date), # fecha del commit
commits[i].message] # mensaje asociado al commit
i+=1
return simplejson.dumps(resp_json)
示例11: get_head
def get_head(repository, commit):
path = settings.REPOSITORY_PATH
if (path[len(path)-2] != '/'):
path += '/'
repo = git.Repo(path+repository)
head = repo.commits(commit)[0]
n_parents = len(head.parents)
resp_json = {"id": head.id, "parents": n_parents}
i=0
while i < n_parents:
resp_json[str(i)]=head.parents[i].id
i+=1
resp_json["tree"] = head.tree.id
resp_json["author_name"] = head.author.name
resp_json["author_email"] = head.author.email
resp_json["fecha_creacion"] = time.asctime(head.authored_date)
resp_json["committer_name"] = head.committer.name
resp_json["committer_email"] = head.committer.email
resp_json["fecha_commit"] = time.asctime(head.committed_date)
resp_json["message"] = head.message
return simplejson.dumps(resp_json)
示例12: log_sig_exit
def log_sig_exit(type, mssg, sigevent_url):
"""
Send a message to the log, to sigevent, and then exit.
Arguments:
type -- 'INFO', 'WARN', 'ERROR'
mssg -- 'message for operations'
sigevent_url -- Example: 'http://[host]/sigevent/events/create'
"""
# Add "Exiting" to mssg.
mssg=str().join([mssg, ' Exiting colormap2vrt.'])
# Send to sigevent.
try:
sent=sigevent(type, mssg, sigevent_url)
except urllib2.URLError:
print 'sigevent service is unavailable'
# Send to log.
if type == 'INFO':
log_info_mssg_with_timestamp(mssg)
elif type == 'WARN':
logging.warning(time.asctime())
logging.warning(mssg)
elif type == 'ERROR':
logging.error(time.asctime())
logging.error(mssg)
# Exit.
sys.exit()
示例13: SendPacket
def SendPacket(self, s, type):
BUFFER_SIZE = 1024
Packet = [self.Kod]
Packet.append(self.Len[0])
Packet.append(self.Len[1])
Packet.append(self.RetranNum)
Packet.append(self.Flag)
Packet.append(self.MyAdd[0])
Packet.append(self.MyAdd[1])
Packet.append(self.MyAdd[2])
Packet.append(self.DestAdd[0])
Packet.append(self.DestAdd[1])
Packet.append(self.DestAdd[2])
Packet.append(self.Tranzaction)
Packet.append(self.PacketNumber)
Packet.append(self.PacketItem)
for i in range(0, len(self.Data)):
Packet.append(self.Data[i])
lenght = len(Packet)
lenght += 2
self.Len[0] = lenght & 0xFF
self.Len[1] = (lenght >> 8) & 0xFF
Packet[1] = self.Len[0]
Packet[2] = self.Len[1]
CRC = RTM64CRC16(Packet, len(Packet))
Packet.append(CRC & 0xFF)
Packet.append((CRC >> 8) & 0xFF)
data_s = []
if type == 1:
Packet_str = bytearray(Packet[0:])
print(Packet_str)
time_start = time.time()
s.send(Packet_str)
s.settimeout(1)
# data = s.recvfrom(BUFFER_SIZE)
try:
data = s.recv(BUFFER_SIZE)
self.OkReceptionCnt += 1
time_pr = time.time() - time_start
# data = char_to_int(data_s,len(data_s))
for i in range(0, len(data)):
data_s.append(data[i])
# data_s = "".join(data)
print(data_s, self.OkReceptionCnt)
print(time_pr, "s")
print(len(data))
except socket.timeout:
self.Errorcnt += 1
print("TCP_RecvError", self.Errorcnt)
print(time.asctime())
error_log = open("error_log_TCP.txt", "a")
error_log.write("TCP_RecvError" + time.asctime() + str(self.Errorcnt) + "\n")
error_log.close()
elif type == 0:
print(Packet)
send_log = open("send_log.txt", "a")
send_log.write(str(Packet))
send_log.close()
s.write(Packet)
return data_s
示例14: createTorr
def createTorr(filename):
# get the time in a convinient format
seconds = int(config["end"]) - int(config["start"])
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
humantime = "%02d:%02d:%02d" % (h, m, s)
if config["debug"]:
print >> sys.stderr, time.asctime(), "-", "duration for the newly created torrent: ", humantime
dcfg = DownloadStartupConfig()
# dcfg.set_dest_dir(basename)
tdef = TorrentDef()
tdef.add_content(filename, playtime=humantime)
tdef.set_tracker(SESSION.get_internal_tracker_url())
print >> sys.stderr, time.asctime(), "-", tdef.get_tracker()
tdef.finalize()
if config["torrName"] == "":
torrentbasename = config["videoOut"] + ".torrent"
else:
torrentbasename = config["torrName"] + ".torrent"
torrentfilename = os.path.join(config["destdir"], torrentbasename)
tdef.save(torrentfilename)
if config["seedAfter"]:
if config["debug"]:
print >> sys.stderr, time.asctime(), "-", "Seeding the newly created torrent"
d = SESSION.start_download(tdef, dcfg)
d.set_state_callback(state_callback, getpeerlist=False)
示例15: listening
def listening(self):
"""
loop in which the client waits for the servers bewegeString and answers
with his calculated destination
after we get 'Ende' the ssl connection will be closed
"""
while True:
try:
bewegeString = read(self.connection)
if self.worldSize == None:
write(self.connection, 'Weltgroesse?')
self.worldSize = read(self.connection)
print 'world size:', self.worldSize
print 'bewegeString=' + bewegeString #string which is given by the server
if 'Ende' in bewegeString:
break
#sending our calculated destination
destination = str(self.beast.bewege(bewegeString))
if len(destination) > 0 and destination != 'None':
print 'sent=' + destination
write(self.connection, destination)
except Exception as e:
print time.asctime(), e, ': lost connection to Server'
break
self.connection.close()