-
- Color
https://i.stack.imgur.com/k2VzI.png
- Disable maplotlib shortcuts
>>> import matplotlib.pyplot as plt
>>> plt.rcParams['keymap.save']
's'
>>> plt.rcParams['keymap.save'] = ''
#The full list of shortcuts
>>> plt.rcParams
- "Allocated too many blocks" error
plt.rcParams['agg.path.chunksize'] = 20000
- Plot in a loop
f = plt.figure(figsize=(16,12))
axMat = range(4)
axMat[0] = f.add_axes([leftMargin, belowMargin+height*3, width, height])
axMat[1] = f.add_axes([leftMargin, belowMargin+height*2, width, height])
axMat[2] = f.add_axes([leftMargin, belowMargin+height, width, height])
axMat[3] = f.add_axes([leftMargin, belowMargin, width, height])
while True:
for i in range(4):
axMat[i].clear()
axMat[i].plot(xMat, dataMat)
plt.savefig(figName+'.png', dpi=100)
- Archive files with compression
import os
import tarfile
#Archive the files in locDir
os.chdir(locDir)
fileMat = os.listdir(locDir)
fidArchive = tarfile.open("archiveFile.tar.bz2", "w:bz2")
for fileName in fileMat:
fidArchive.add(fileName)
fidArchive.close()
- Search a file or directory
import glob
glob.glob('D:\\*\\data\\')
Out[12]: ['D:\\BOLT\\data\\', 'D:\\LMA\\data\\']
- Find out the most common element in an array (only work for positive elements)
x = np.array([9, 3, 5, 2, 3, 4, 2, 3, 5, 7, 5, 1, 5, 0])
np.bincount(x).argmax()
Out[7]: 5
- Write Compressed binary file
import bz2
from struct import pack
fid = bz2.BZ2File(fileName+'.bz2', 'wb')
dataId = pack(str(dataLen)+'h', *dataMat)
fid.write(dataId)
- Execute another python scipt
subprocess.call('python script.py', stdout=open('log.txt', 'wt'), stderr=open('log.txt', 'wt'), shell=True)
#Without waiting
subprocess.Popen(['nohup', 'python', 'script.py'], preexec_fn=os.setpgrp)
- Print exception error message
try:
#Do someting
except Exception, e:
print str(e)
- Get IP address
from urllib2 import urlopen
strIP = urlopen('http://ip.42.pl/raw').read()
strIP
Out[2]: '133.66.192.206'
- Plot in a SSH session
#Put this before other imports
import matplotlib
matplotlib.use('Agg')
- Matplotlib change tick labels
f = plt.figure(figsize=(15,8))
ax = f.add_axes([0.08, 0.08, 0.85, 0.85])
ax.plot(timeMat, valMat)
tickMat = ax.get_xticks()
tickLabelMat = [datetime.datetime.fromtimestamp(tickVal).strftime('%Y-%m-%d') for tickVal in tickMat]
ax.set_xticklabels(tickLabelMat)
plt.show()
- String find and replace
s
Out[10]: '1,431,112'
s.find(',')
Out[11]: 1
s.find(',', 3)
Out[12]: 5
s.rfind(',')
Out[13]: 5
s.replace(',', '')
Out[14]: '1431112'
- Plot Japan Map
import scipy.io
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 5))
mat = scipy.io.loadmat('E:\\LF\\code\\map\\japanmap.mat')
plt.plot(mat['lon'], mat['lat'], c='k')
Download japanmap.mat
- readable time -> linux time
import datetime
import time
strNaturalTime = '20120102030405'
linuxSec = time.mktime(datetime.datetime.strptime(strNaturalTime, '%Y%m%d%H%M%S').timetuple())
print linuxSec
>>>
1325473445.0
- linux time -> readable time
#Change linux time stamp (for example: 1234567890) to readable time (The result depends on the time zone of your computer).
import datetime
naturalTime = datetime.datetime.fromtimestamp(1234567890).strftime(' %Y%m%d %H:%M:%S')
print naturalTime
>>>
20090213 23:31:30
- Get index of a sorted mat
import numpy as np
sMat = ['b', 'lkk', 'abd', 'lll', '098', '0']
np.argsort(sMat)
Out[36]: array([5, 4, 2, 0, 1, 3], dtype=int64)
- Ftp
from ftplib import FTP
ftp_add = '123.123.123.123'
ftp_port = 21
ftp_account = 'account'
ftp_key = 'pass'
ftpDir = '/dir/'
#log in
ftp = FTP()
ftp.connect(ftp_add, ftp_port)
ftp.login(ftp_account, ftp_key)
#Change directory
ftp.cwd(ftpDir)
#Download
fidFile = open('locName', 'wb')
ftp.retrbinary('RETR '+'ftpFileName', fidFile.write)
fidFile.close()
#Upload
fidFile = open('locName', 'rb')
ftp.storbinary('STOR '+'ftpFileName', fidFile)
fidFile.close()
#file list
fileMat = ftp.nlst()
fileNum = len(fileMat) #fileNum is 2 for an empty folder
#Quit
ftp.quit()