def getos():
dagitim=platform.dist()
dagitim=dagitim[0]
mimari=platform.machine()
osys=platform.system()
unumber = os.getuid()
zaman=time.ctime()
if unumber==0:
kulanici="root"
else:
kulanici="No root"
bilgi="""
============================
CPU: {}
OS: {}
DAGITIM: {}
KULANICI: {}
ZAMAN: {}
============================""".format(mimari,osys,dagitim,kulanici,zaman)
print(bilgi)
python类ctime()的实例源码
def logBasicSettings():
# record basic user inputs and settings to log file for future purposes
import getpass, time
f = open(textFilePath,'a+')
f.write("\n################################################################################################################\n")
f.write("Executing \"Export SSURGO Shapefiles\" tool\n")
f.write("User Name: " + getpass.getuser() + "\n")
f.write("Date Executed: " + time.ctime() + "\n")
f.write("User Parameters:\n")
f.write("\tFile Geodatabase Feature Dataset: " + inLoc + "\n")
f.write("\tExport Folder: " + outLoc + "\n")
#f.write("\tArea of Interest: " + AOI + "\n")
f.close
del f
## ===================================================================================
def save(self):
# save frames info, do not overwrite.
filepath = os.path.join(self.framedir, 'frames.json')
obj = {
'ctime' : time.ctime(),
'device' : self.device_info,
'frames' : self.frames,
}
with open(filepath, 'w') as f:
json.dump(obj, f, indent=2)
# save draft info
filepath = os.path.join(self.framedir, 'draft.json')
with open(filepath, 'w') as f:
json.dump(self.case_draft, f, indent=2)
# make a copy at casedir
filepath = os.path.join(self.casedir, 'case.json')
with open(filepath, 'w') as f:
json.dump(self.case_draft, f, indent=2)
# generate_script
self.generate_script()
def test_max_timeout(context, event_loop):
temp_dir = os.path.join(context.config['work_dir'], "timeout")
context.config['task_script'] = (
sys.executable, TIMEOUT_SCRIPT, temp_dir
)
context.config['task_max_timeout'] = 3
event_loop.run_until_complete(task.run_task(context))
try:
event_loop.run_until_complete(asyncio.sleep(10)) # Let kill() calls run
except RuntimeError:
pass
files = {}
for path in glob.glob(os.path.join(temp_dir, '*')):
files[path] = (time.ctime(os.path.getmtime(path)), os.stat(path).st_size)
print("{} {}".format(path, files[path]))
for path in glob.glob(os.path.join(temp_dir, '*')):
print("Checking {}...".format(path))
assert files[path] == (time.ctime(os.path.getmtime(path)), os.stat(path).st_size)
assert len(files.keys()) == 6
# claim_work {{{1
def log(level, console_color, html_color, fmt, *args, **kwargs):
global last_no, buffer_lock, buffer, buffer_size
string = '%s - [%s] %s\n' % (time.ctime()[4:-5], level, fmt % args)
buffer_lock.acquire()
try:
set_console_color(console_color)
sys.stderr.write(string)
set_console_color(reset_color)
last_no += 1
buffer[last_no] = string
buffer_len = len(buffer)
if buffer_len > buffer_size:
del buffer[last_no - buffer_size]
except Exception as e:
string = '%s - [%s]LOG_EXCEPT: %s, Except:%s<br>' % (time.ctime()[4:-5], level, fmt % args, e)
last_no += 1
buffer[last_no] = string
buffer_len = len(buffer)
if buffer_len > buffer_size:
del buffer[last_no - buffer_size]
finally:
buffer_lock.release()
#=================================================================
def flatten(self, msg, unixfrom=False):
"""Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. If the original message
has no From_ delimiter, a `standard' one is crafted. By default, this
is False to inhibit the printing of any From_ delimiter.
Note that for subobjects, no From_ line is printed.
"""
if unixfrom:
ufrom = msg.get_unixfrom()
if not ufrom:
ufrom = 'From nobody ' + time.ctime(time.time())
print >> self._fp, ufrom
self._write(msg)
def view_reading_list(opts):
"""
get the current reading list
:param opts:
"""
if os.path.isfile(READING_LIST_ENTRY_FILE_PATH):
with open(READING_LIST_ENTRY_FILE_PATH) as reading_list_entry:
file_contents = yaml.load(reading_list_entry)
file_contents = dict(file_contents)
last_updated = time.ctime(os.path.getmtime(READING_LIST_ENTRY_FILE_PATH))
query = opts[1]
params = opts[0]
search = ''
if query != 'None':
search = "(filtered by " + params + ": " + query + ")"
filtered_contents = [article for article in file_contents['entries'] if
is_in_params(params, query, article)]
file_contents = dict(entries=filtered_contents)
chalk.blue("Your awesome reading list " + search)
chalk.blue("Last updated: " + last_updated)
print_reading_list(file_contents)
else:
empty_list_prompt()
def crawl(url):
"""
????URL?????????????????
"""
try:
html = requests.get(url)
except:
with open("log.log","a") as file:
file.write("Http error on " + time.ctime())
time.sleep(60)
return None
soup = BeautifulSoup(html.text, 'lxml')
data_list = []
for cont in soup.find_all("div", {"class":"content"}):
raw_data = cont.get_text()
data = raw_data.replace("\n","")
data_list.append(data)
return data_list
def flatten(self, msg, unixfrom=False):
"""Print the message object tree rooted at msg to the output file
specified when the Generator instance was created.
unixfrom is a flag that forces the printing of a Unix From_ delimiter
before the first object in the message tree. If the original message
has no From_ delimiter, a `standard' one is crafted. By default, this
is False to inhibit the printing of any From_ delimiter.
Note that for subobjects, no From_ line is printed.
"""
if unixfrom:
ufrom = msg.get_unixfrom()
if not ufrom:
ufrom = 'From nobody ' + time.ctime(time.time())
print >> self._fp, ufrom
self._write(msg)
def OnKeyboardEvent(event):
global yourgmail, yourgmailpass, sendto, interval
data = '\n[' + str(time.ctime().split(' ')[3]) + ']' \
+ ' WindowName : ' + str(event.WindowName)
data += '\n\tKeyboard key :' + str(event.Key)
data += '\n===================='
global t, start_time
t = t + data
if len(t) > 500:
f = open('Logfile.txt', 'a')
f.write(t)
f.close()
t = ''
if int(time.time() - start_time) == int(interval):
Mail_it(t, pics_names)
t = ''
return True
def info(log:str,target='console'):
"""
log: text to record.
target: 'console' to print log on screen or file to write in.
"""
if target=='console':
thd=threading.Thread(target=print,args=(ctime(),':',log))
thd.setDaemon(True)
thd.start()
thd.join()
else:
try:
thd=threading.Thread(target=print,args=(ctime(),':',log))
thd.setDaemon(True)
thd.start()
thd.join()
except Exception as e:
print(e)
def check_file_freshness(filename, newer_than=3600):
"""
Check a file exists, is readable and is newer than <n> seconds (where
<n> defaults to 3600).
"""
# First check the file exists and is readable
if not os.path.exists(filename):
raise CriticalError("%s: does not exist." % (filename))
if os.access(filename, os.R_OK) == 0:
raise CriticalError("%s: is not readable." % (filename))
# Then ensure the file is up-to-date enough
mtime = os.stat(filename).st_mtime
last_modified = time.time() - mtime
if last_modified > newer_than:
raise CriticalError("%s: was last modified on %s and is too old "
"(> %s seconds)."
% (filename, time.ctime(mtime), newer_than))
if last_modified < 0:
raise CriticalError("%s: was last modified on %s which is in the "
"future."
% (filename, time.ctime(mtime)))
def download_course_tarball(self):
'''
Download tar.gz of full course content (via Studio)
'''
self.ensure_studio_site()
if self.verbose:
print "Downloading tar.gz for %s" % (self.course_id)
url = '%s/export/%s?_accept=application/x-tgz' % (self.BASE, self.course_id)
r3 = self.ses.get(url)
if not r3.ok or (r3.status_code==404):
url = '%s/export/slashes:%s+%s?_accept=application/x-tgz' % (self.BASE, self.course_id.replace('/','+'), sem)
r3 = self.ses.get(url)
dt = time.ctime(time.time()).replace(' ','_').replace(':','')
ofn = '%s/COURSE-%s___%s.tar.gz' % (self.data_dir, self.course_id.replace('/','__'), dt)
self.ensure_data_dir_exists()
with open(ofn, 'w') as fp:
fp.write(r3.content)
print "--> %s" % (ofn)
return ofn
def cache_it(self, key, f, time_expire):
if self.debug:
self.r_server.incr('web2py_cache_statistics:misses')
cache_set_key = self.cache_set_key
expireat = int(time.time() + time_expire) + 120
bucket_key = "%s:%s" % (cache_set_key, expireat / 60)
value = f()
value_ = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
if time_expire == 0:
time_expire = 1
self.r_server.setex(key, time_expire, value_)
#print '%s will expire on %s: it goes in bucket %s' % (key, time.ctime(expireat))
#print 'that will expire on %s' % (bucket_key, time.ctime(((expireat/60) + 1)*60))
p = self.r_server.pipeline()
#add bucket to the fixed set
p.sadd(cache_set_key, bucket_key)
#sets the key
p.setex(key, time_expire, value_)
#add the key to the bucket
p.sadd(bucket_key, key)
#expire the bucket properly
p.expireat(bucket_key, ((expireat / 60) + 1) * 60)
p.execute()
return value
def getTimeTagStr(self):
"""Return the TimeTag as a human-readable string
"""
fract, secs = math.modf(self.timetag)
out = time.ctime(secs)[11:19]
out += ("%.3f" % fract)[1:]
return out
def getTimeTagStr(self):
"""Return the TimeTag as a human-readable string
"""
fract, secs = math.modf(self.timetag)
out = time.ctime(secs)[11:19]
out += ("%.3f" % fract)[1:]
return out
def main_process(self, topicId):
# print id
reqdata = {'liveId': topicId}
# ?????
reqheaders = {'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Host': 'h5-zb.leju.com',
'X-Requested-With': 'XMLHttpRequest',
'Origin': 'http://h5-zb.leju.com',
'Referer': 'http://zhichang.renren.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0',}
#'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36', }
time.sleep(random.random())
while True:
nowTime = time.ctime()
r = requests.post(self.url, data=reqdata, headers=reqheaders)
msg = '====' + topicId +'===='
tmpDict = r.json()
if ('errorMsg' in tmpDict):
errMsg = tmpDict['errorMsg']
print (nowTime + msg + errMsg)
if ('result' in tmpDict):
print (nowTime + msg + str(tmpDict['result']))
time.sleep(60.33);
def get_cnonce(self, nonce):
# The cnonce-value is an opaque
# quoted string value provided by the client and used by both client
# and server to avoid chosen plaintext attacks, to provide mutual
# authentication, and to provide some message integrity protection.
# This isn't a fabulous effort, but it's probably Good Enough.
dig = hashlib.sha1("%s:%s:%s:%s" % (self.nonce_count, nonce, time.ctime(),
randombytes(8))).hexdigest()
return dig[:16]
def GenerateBanner(self):
return '/* This file has been automatically generated, you must _NOT_ edit it directly. (%s) */\n' % time.ctime()
# Private methods
def _cnonce():
dig = _md5("%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])).hexdigest()
return dig[:16]