def open_game_resources(wow_path):
"""Open game resources and store links to them in memory"""
print("\nProcessing available game resources of client: " + wow_path)
start_time = time.time()
if WoWFileData.is_wow_path_valid(wow_path):
data_packages = WoWFileData.list_game_data_paths(os.path.join(wow_path, "Data\\"))
resource_map = []
for package in data_packages:
if os.path.isfile(package):
resource_map.append((mpyq.MPQArchive(package, listfile=False), True))
print("\nLoaded MPQ: " + os.path.basename(package))
else:
resource_map.append((package, False))
print("\nLoaded folder patch: " + os.path.basename(package))
print("\nDone initializing data packages.")
print("Total loading time: ", time.strftime("%M minutes %S seconds", time.gmtime(time.time() - start_time)))
return resource_map
else:
print("\nPath to World of Warcraft is empty or invalid. Failed to load game data.")
return None
python类strftime()的实例源码
def log(self, message, *args):
now = time.time()
if args:
message = message % args
if self.log_ms:
self.stream.write('%s.%03d %s - %s\n' %
(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
1000 * (now - int(now)), self.name, message))
else:
self.stream.write('%s %s - %s\n' %
(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
self.name, message))
def log(self, message, *args):
now = time.time()
if args:
message = message % args
if self.log_ms:
self.stream.write('%s.%03d %s - %s\n' %
(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
1000 * (now - int(now)), self.name, message))
else:
self.stream.write('%s %s - %s\n' %
(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)),
self.name, message))
def get_requirements():
return '''
import os
import re
import sys
import math
import time
import socket
import base64
import shutil
import ctypes
import socket
import struct
import zipfile
import datetime
import requests
import StringIO
import platform
import threading
import subprocess
from Crypto import Random
from Crypto.Cipher import AES
from mss import ScreenshotError
from time import strftime, sleep
from contextlib import contextmanager
from base64 import b64decode as INFO
from zlib import decompress as SEC
from st_utils import *
from st_protocol import *
from st_encryption import *
'''
def current_time():
return strftime(Res.time_format, gmtime())
def save_rdd_contents(rdd):
file_name = "".join((
"/vagrant_home/uniq_metrics",
'-', time.strftime("%Y-%m-%d-%H-%M-%S"),
'-', str(rdd.id),
'.log'))
rdd.saveAsTextFile(file_name)
def saveLights(self):
# We'll now save the lights down to a JSON file that can be shared as a preset
# The properties dictionary will hold all the light properties to save down
properties = {}
# First lets get all the light widgets that exist in our manager
for lightWidget in self.findChildren(LightWidget):
# For each widget we can get its' light object
light = lightWidget.light
# Then we need to get its transform node
transform = light.getTransform()
# Finally we add it to the dictionary.
# The key will be the name of the transform which we get by converting the node to a string
# Then we simply query the attributes of the light that we want to save down
properties[str(transform)] = {
'translate': list(transform.translate.get()),
'rotation': list(transform.rotate.get()),
'lightType': pm.objectType(light),
'intensity': light.intensity.get(),
'color': light.color.get()
}
# We fetch the light manager directory to save in
directory = self.getDirectory()
# We then construct the name of the lightFile to save
# We'll be using time.strftime to construct a name using the current time
# %m%d will give 0701 for July 1st (month and day)
# so we'd end up with a name like lightFile_0701.json stored in our directory
lightFile = os.path.join(directory, 'lightFile_%s.json' % time.strftime('%m%d'))
# Next we open the file to write
with open(lightFile, 'w') as f:
# Then we use json to write out our file to this location
json.dump(properties, f, indent=4)
# A helpful logger call tells us where the file was saved to.
logger.info('Saving file to %s' % lightFile)
def saveLights(self):
# We'll now save the lights down to a JSON file that can be shared as a preset
# The properties dictionary will hold all the light properties to save down
properties = {}
# First lets get all the light widgets that exist in our manager
for lightWidget in self.findChildren(LightWidget):
# For each widget we can get its' light object
light = lightWidget.light
# Then we need to get its transform node
transform = light.getTransform()
# Finally we add it to the dictionary.
# The key will be the name of the transform which we get by converting the node to a string
# Then we simply query the attributes of the light that we want to save down
properties[str(transform)] = {
'translate': list(transform.translate.get()),
'rotation': list(transform.rotate.get()),
'lightType': pm.objectType(light),
'intensity': light.intensity.get(),
'color': light.color.get()
}
# We fetch the light manager directory to save in
directory = self.getDirectory()
# We then construct the name of the lightFile to save
# We'll be using time.strftime to construct a name using the current time
# %m%d will give 0701 for July 1st (month and day)
# so we'd end up with a name like lightFile_0701.json stored in our directory
lightFile = os.path.join(directory, 'lightFile_%s.json' % time.strftime('%m%d'))
# Next we open the file to write
with open(lightFile, 'w') as f:
# Then we use json to write out our file to this location
json.dump(properties, f, indent=4)
# A helpful logger call tells us where the file was saved to.
logger.info('Saving file to %s' % lightFile)
def sec_to_text(ts):
return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts))
def showUser(user, fullInfo):
def line(key, value):
if value:
printLine("%s : %s" % (key.ljust(16, " "), value))
separator("#", "USER INFO")
line('Username', user.username)
line('Name', user.name)
line('Email', user.email)
if fullInfo:
limit = (int(user.accounting.uploadLimit) / 1024 / 1024)
endlimit = time.gmtime(user.accounting.uploadLimitEnd / 1000)
line('Upload limit', "%.2f" % limit)
line('Upload limit end', time.strftime("%d.%m.%Y", endlimit))
def printDate(timestamp):
# Author @ash-2000 https://github.com/ash-2000
# Check for crashing when timestamp is 13 digits on python2.7
# pull request #260
if len(str(timestamp)) == 13:
timestamp = int(str(timestamp)[0:-3])
# ---
return datetime.date.strftime(datetime.date.fromtimestamp(timestamp / 1000), "%d.%m.%Y")
def print_and_log(text, error=False):
print(text)
if error:
logging.error(time.strftime(LOG_TIME_FORMAT) + text)
else:
logging.info(time.strftime(LOG_TIME_FORMAT) + text)
def proccessComments():
for comment in reddit.redditor(str(reddit.user.me())).comments.new(limit=None):
#if comment score is below the threshold, delete it
if comment.score < deleteThreshold:
comment.delete()
permalink = "http://www.reddit.com" + \
comment.permalink() + "/"
print("Deleting comment: " + permalink)
logging.info(time.strftime("%Y/%m/%d %H:%M:%S ") +
"Deleting comment: " + permalink)
def datetime(self, asstruct=False):
if not asstruct:
return time.strftime('%Y-%m-%d %X %Z')
else:
d = time.localtime()
return {
'year': d.tm_year,
'mon': d.tm_mon,
'mday': d.tm_mday,
'hour': d.tm_hour,
'min': d.tm_min,
'sec': d.tm_sec,
'tz': time.strftime('%Z', d),
'str': time.strftime('%Y-%m-%d %X', d),
}
def cpustat(self, fullstat=False):
cpustat = {}
# REF: http://www.kernel.org/doc/Documentation/filesystems/proc.txt
fname = ('used', 'idle')
full_fname = ('user', 'nice', 'system', 'idle', 'iowait', 'irq',
'softirq', 'steal', 'guest', 'guest_nice')
cpustat['cpus'] = []
with open('/proc/stat', 'r') as f:
for line in f:
if line.startswith('cpu'):
fields = line.strip().split()
name = fields[0]
if not fullstat and name != 'cpu': continue;
stat = fields[1:]
stat = [int(i) for i in stat]
statall = sum(stat)
if fullstat:
while len(stat) < 10: stat.append(0)
stat = dict(zip(full_fname, stat))
else:
stat = [statall-stat[3], stat[3]]
stat = dict(zip(fname, stat))
stat['all'] = statall
if name == 'cpu':
cpustat['total'] = stat
else:
cpustat['cpus'].append(stat)
elif line.startswith('btime'):
btime = int(line.strip().split()[1])
cpustat['btime'] = time.strftime('%Y-%m-%d %X %Z',
time.localtime(btime))
return cpustat
def format_duration(self, duration):
if (duration <= 0) and self.max is None or self.cur == self.min:
result = '??:??:??'
#elif duration < 1:
# result = '--:--:--'
else:
result = time.strftime('%H:%M:%S', time.gmtime(duration))
return result
def update_headers(self, resp):
headers = resp.headers
if 'expires' in headers:
return {}
if 'cache-control' in headers and headers['cache-control'] != 'public':
return {}
if resp.status not in self.cacheable_by_default_statuses:
return {}
if 'date' not in headers or 'last-modified' not in headers:
return {}
date = calendar.timegm(parsedate_tz(headers['date']))
last_modified = parsedate(headers['last-modified'])
if date is None or last_modified is None:
return {}
now = time.time()
current_age = max(0, now - date)
delta = date - calendar.timegm(last_modified)
freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
if freshness_lifetime <= current_age:
return {}
expires = date + freshness_lifetime
return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))}
def tags(self):
version = ''
if self.tag_build:
version += self.tag_build
if self.tag_date:
version += time.strftime("-%Y%m%d")
return version