def connectionMade(self):
def func(f,path,names):
names.sort(lambda x,y:cmp(string.lower(x),string.lower(y)))
for n in names:
name=os.path.join(path,n)
lt=time.localtime(os.path.getmtime(name))
size=os.path.getsize(name)
f[1]=f[1]+size
f.append("%02d/%02d/%4d %02d:%02d %8d %s" %
(lt[1],lt[2],lt[0],lt[3],lt[4],size,name[f[0]:]))
f=[len(self.dir)+1,0]
os.path.walk(self.dir,func,f)
size=f[1]
self.listing=string.join(f[2:],"\r\n")+"\r\n"
open("\\listing.txt","w").write(self.listing)
hdr=["OFT2",256,0x1108,self.cookie,0,0,len(f)-2,len(f)-2,1,1,size,
len(self.listing),os.path.getmtime(self.dir),
checksum(self.listing),0,0,0,0,0,0,"OFT_Windows ICBMFT V1.1 32",
"\002",chr(0x1a),chr(0x10),"","",0,0,""]
self.transport.write(apply(struct.pack,[self.header_fmt]+hdr))
python类localtime()的实例源码
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 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 list(self, verbose=True):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
"""
self._check()
for tarinfo in self:
if verbose:
print(filemode(tarinfo.mode), end=' ')
print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid), end=' ')
if tarinfo.ischr() or tarinfo.isblk():
print("%10s" % ("%d,%d" \
% (tarinfo.devmajor, tarinfo.devminor)), end=' ')
else:
print("%10d" % tarinfo.size, end=' ')
print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6], end=' ')
print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
if verbose:
if tarinfo.issym():
print("->", tarinfo.linkname, end=' ')
if tarinfo.islnk():
print("link to", tarinfo.linkname, end=' ')
print()
def list(self, verbose=True, *, members=None):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced. `members' is optional and must be a subset of the
list returned by getmembers().
"""
self._check()
if members is None:
members = self
for tarinfo in members:
if verbose:
_safe_print(stat.filemode(tarinfo.mode))
_safe_print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid))
if tarinfo.ischr() or tarinfo.isblk():
_safe_print("%10s" %
("%d,%d" % (tarinfo.devmajor, tarinfo.devminor)))
else:
_safe_print("%10d" % tarinfo.size)
_safe_print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6])
_safe_print(tarinfo.name + ("/" if tarinfo.isdir() else ""))
if verbose:
if tarinfo.issym():
_safe_print("-> " + tarinfo.linkname)
if tarinfo.islnk():
_safe_print("link to " + tarinfo.linkname)
print()
def exeTime(func):
def newFunc(*args, **args2):
t0 = time.time()
print "%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__)
print '------------------- begin ------------------------'
back = func(*args, **args2)
print '-------------------- end -------------------------'
print "%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__)
print "%.8fs taken for {%s}" % (time.time() - t0, func.__name__)
return back
return newFunc
def list(self, verbose=True):
"""Print a table of contents to sys.stdout. If `verbose' is False, only
the names of the members are printed. If it is True, an `ls -l'-like
output is produced.
"""
self._check()
for tarinfo in self:
if verbose:
print(filemode(tarinfo.mode), end=' ')
print("%s/%s" % (tarinfo.uname or tarinfo.uid,
tarinfo.gname or tarinfo.gid), end=' ')
if tarinfo.ischr() or tarinfo.isblk():
print("%10s" % ("%d,%d" \
% (tarinfo.devmajor, tarinfo.devminor)), end=' ')
else:
print("%10d" % tarinfo.size, end=' ')
print("%d-%02d-%02d %02d:%02d:%02d" \
% time.localtime(tarinfo.mtime)[:6], end=' ')
print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')
if verbose:
if tarinfo.issym():
print("->", tarinfo.linkname, end=' ')
if tarinfo.islnk():
print("link to", tarinfo.linkname, end=' ')
print()
def output(self, out_text, exit_code):
# print the output in the text_output widget (QTextEdit)
# success
if exit_code==0:
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#00aa00">Success</font>]')
# failure
else:
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#ff0000">Failure</font>]')
#
# Print the output in the GUI with a timestamp but without exit_code
# this function should be used instead of other form of output printing
#
def direct_output(self, out_text):
# print the output in the text_output widget (QTextEdit)
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text)
#
# Check if the requested options are consistent
#
def output(self, out_text, exit_code):
# print the output in the text_output widget (QTextEdit)
# success
if exit_code==0:
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#00aa00">Success</font>]')
# failure
else:
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text + ' [<font color="#ff0000">Failure</font>]')
#
# Print the output in the GUI with a timestamp but without exit_code
# this function should be used instead of other form of output printing
#
def direct_output(self, out_text):
# print the output in the text_output widget (QTextEdit)
self.text_output.append( '<b>' + time.strftime("%H:%M:%S", time.localtime()) + '</b> - ' + out_text)
#
# Check if the requested options are consistent
#
def token_saver(token):
"""Saves the token json/dict format inside deviantartdb.sqlite on Table: deviantart_session.
token_saver argument parameters:
- token: The argument should be a variable in json/dict format:
{"expires_in": 3600, "status": "success", "access_token": "Alph4num3r1ct0k3nv4lu3", "token_type": "Bearer"}"""
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.executescript('''DROP TABLE IF EXISTS deviantart_session;
CREATE TABLE deviantart_session( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`token` TEXT, 'expires_at' varchar(64) )''')
token_dump=json.dumps(token)
token=json.loads(token_dump)
expires_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(token['expires_at']))
cur.execute('''INSERT INTO deviantart_session (token, expires_at) VALUES ( ?, ? ) ''', (token_dump, expires_at) )
conn.commit()
cur.close()
def get_token():
"""Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from DeviantArt"""
token_url='https://www.deviantart.com/oauth2/token'
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.execute('''SELECT token FROM deviantart_session''')
token=None
for row in cur: #if the table on token FROM deviantart_session is empty, this for loop step is just skipped
try:
token = json.loads(row[0])
print 'Adquiring token from deviantartdb.sqlite database...'
except:
print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n"
if token==None:
print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
else:
timenow=time.time()
if timenow>token['expires_at']:
print 'The token on database is expired. Adquiring new access token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
cur.close()
print 'Token:\n', json.dumps(token, indent=3)
print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n"
token_saver(token)
return token
def get_token():
"""Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from https://www.deviantart.com/oauth2/token"""
token_url='https://www.deviantart.com/oauth2/token'
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.execute('''SELECT token FROM deviantart_session''')
token=None
for row in cur:
try:
token = json.loads(row[0])
print 'Adquiring token from deviantartdb.sqlite database...'
except:
print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n"
if token==None:
print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
else:
timenow=time.time()
if timenow>token['expires_at']:
print 'The token on database is expired. Adquiring new access token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
cur.close()
print 'Token:\n', json.dumps(token, indent=3)
print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n"
token_saver(token)
return token
def token_saver(token):
"""Saves the token json/dict format inside deviantartdb.sqlite on Table: deviantart_session.
token_saver argument parameters:
- token: The argument should be a variable in json/dict format:
{"expires_in": 3600, "status": "success", "access_token": "Alph4num3r1ct0k3nv4lu3", "token_type": "Bearer"}"""
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.executescript('''DROP TABLE IF EXISTS deviantart_session;
CREATE TABLE deviantart_session( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`token` TEXT, 'expires_at' varchar(64) )''')
token_dump=json.dumps(token)
token=json.loads(token_dump)
expires_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(token['expires_at']))
cur.execute('''INSERT INTO deviantart_session (token, expires_at) VALUES ( ?, ? ) ''', (token_dump, expires_at) )
conn.commit()
cur.close()
def get_token():
"""Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from https://www.deviantart.com/oauth2/token"""
token_url='https://www.deviantart.com/oauth2/token'
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.execute('''SELECT token FROM deviantart_session''')
token=None
for row in cur:
try:
token = json.loads(row[0])
print 'Adquiring token from deviantartdb.sqlite database...'
except:
print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n"
if token==None:
print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
else:
timenow=time.time()
if timenow>token['expires_at']:
print 'The token on database is expired. Adquiring new access token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
cur.close()
print 'Token:\n', json.dumps(token, indent=3)
print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n"
token_saver(token)
return token
def get_token():
"""Returns the token inside deviantartdb.sqlite. If no token exists on database or it is expired, fetch a new one from https://www.deviantart.com/oauth2/token"""
token_url='https://www.deviantart.com/oauth2/token'
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.execute('''SELECT token FROM deviantart_session''')
token=None
for row in cur:
try:
token = json.loads(row[0])
print 'Adquiring token from deviantartdb.sqlite database...'
except:
print 'Adquiring token from deviantartdb.sqlite FAIL!'"\n"
if token==None:
print 'No token inside deviantartdb.sqlite'"\n"'Adquiring token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
else:
timenow=time.time()
if timenow>token['expires_at']:
print 'The token on database is expired. Adquiring new access token from Deviantart...'
token = deviantart_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
cur.close()
print 'Token:\n', json.dumps(token, indent=3)
print 'Token expires at:', time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(json.dumps(token['expires_at'])))),"\n"
token_saver(token)
return token
def token_saver(token):
"""Saves the token json/dict format inside deviantartdb.sqlite on Table: deviantart_session.
token_saver argument parameters:
- token: The argument should be a variable in json/dict format:
{"expires_in": 3600, "status": "success", "access_token": "Alph4num3r1ct0k3nv4lu3", "token_type": "Bearer"}"""
conn = sqlite3.connect('deviantartdb.sqlite')
cur = conn.cursor()
cur.executescript('''DROP TABLE IF EXISTS deviantart_session;
CREATE TABLE deviantart_session( `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`token` TEXT, 'expires_at' varchar(64) )''')
token_dump=json.dumps(token)
token=json.loads(token_dump)
expires_at=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(token['expires_at']))
cur.execute('''INSERT INTO deviantart_session (token, expires_at) VALUES ( ?, ? ) ''', (token_dump, expires_at) )
conn.commit()
cur.close()