Python 你好,世界

print "hello world"

Python 使用DictMixin在Python中创建类似字典的对象

"""How to create a custom mappable container (dictionary-like) type in Python."""

from UserDict import DictMixin

class MyDict(DictMixin):
    # MyDict only needs to implement getitem, setitem, delitem and keys (at a 
    # minimum) and UserDict will provide the rest of the standard dictionary
    # methods based on these four.
    #
    # getitem and delitem should raise KeyError if no item exists for the given
    # key. getitem, setitem and delitem should raise TypeError if the given key
    # is of the wrong type.

    def __getitem__(self, key):
        ....

    def __setitem__(self, key, item):
        ....

    def __delitem__(self, key):
        ....

    def keys(self):
        ....

# You can now use your class as if it was a dict, using the standard container 
# operators and dictionary methods.

d = MyDict()
d[key] = value
d.get(key)
d.clear()
etc.

Python 在Python中获取主目录路径(win,lin,其他?)

homedir = os.path.expanduser('~')

# ...works on at least windows and linux. 
# In windows it points to the user's folder 
#  (the one directly under Documents and Settings, not My Documents)


# In windows, you can choose to care about local versus roaming profiles.
# You can fetch the current user's through PyWin32.
#
# For example, to ask for the roaming 'Application Data' directory:
#  (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one)
#  (See microsoft references for further CSIDL constants)
try:
    from win32com.shell import shellcon, shell            
    homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
 
except ImportError: # quick semi-nasty fallback for non-windows/win32com case
    homedir = os.path.expanduser("~")

Python 删除变音符号

reCombining = re.compile(u'[\u0300-\u036f\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]',re.U)
 
def remove_diacritics(s):
    " Decomposes string, then removes combining characters "
    return reCombining.sub('',unicodedata.normalize('NFD',unicode(s)) )

Python 包含目录

def containsDir (dirPath):
    contents=os.listdir(dirPath)
    dirList=[item for item in contents if os.path.isdir(os.path.join(dirPath,item))]
    return not dirList==list()

Python 包含存档

def containsArchive (dirPath):
    contents=os.listdir(dirPath)
    archiveExts=['.zip','.rar','.gz','.bz2','.tar','.r01','.r001']
    archiveList=[item for item in contents if os.path.splitext(item)[-1].lower() in archiveExts]
    return not archiveList==list()

Python Git和XCode:一个git构建号脚本

import os
from Foundation import NSMutableDictionary

version = os.popen4("git rev-parse --short HEAD")[1].read()
info = os.environ['INFOPLIST_PATH']

plist = NSMutableDictionary.dictionaryWithContentsOfFile_(info)
plist['CFBundleVersion'] = version
plist.writeToFile_atomically_(info, 1)

Python pickle(cPickle)vs numpy tofile / fromfile

import numpy
import os
import cPickle as pickle
from datetime import datetime

def dt2sec(dt):
    return dt.microseconds / 1000.0 + dt.seconds

data = [ { "a" : numpy.arange( 100, dtype=float ),
           "b" : numpy.arange( 100, dtype=float ).reshape(10,10) }
         for i in range(10)]

pickle_name = "data.pickle"
ff_dir = "fromfile"

os.mkdir( ff_dir )

#----- write data
print "write data"
t0 = datetime.now()
pickle.dump(data, file(pickle_name,"w"))
t1 = datetime.now()
print "pickle.dump :", dt2sec(t1-t0)

t0 = datetime.now()
for i,d in enumerate(data):
    idir = os.path.join(ff_dir,str(i))
    os.mkdir( idir )
    for name, array in d.items():
        # write to fromfile/{i}/{name}
        array.tofile(os.path.join(idir,name))
t1 = datetime.now()
print "tofile :", dt2sec(t1-t0)

#----- read data
print "read data"
t0 = datetime.now()
pickle_data = pickle.load(file(pickle_name))
#print pickle_data
t1 = datetime.now()
print "pickle.load :", dt2sec(t1-t0)

t0 = datetime.now()
ff_data = []
for i in os.listdir(ff_dir):
    idir = os.path.join(ff_dir,i)
    tmp = {}
    for name in os.listdir(idir):
        tmp[name] = numpy.fromfile(os.path.join(idir,name))
    ff_data.append(tmp)
#print ff_data
t1 = datetime.now()
print "fromfile :", dt2sec(t1-t0)


## write data
## pickle.dump : 9.328
## tofile : 2.946
## read data
## pickle.load : 15.423
## fromfile : 1.858

Python 运行Doctest / Docutils

def add(x,y):
    """
    >>> add(5,6)
    11
    """
    return x+y

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Python 从站点链接或具有ram文件的xml链接下载所有* .rm文件

#!/usr/bin/env python
#
#       best.py
#       
#       Copyright 2008 hemanth <hemanth.hm@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.




import commands
import os
import pickle
 
def readDir():
		directory = raw_input('In which folder would you like to save the songs??\n')
		if(os.path.exists(directory)):
				print 'Error!! Please give an other name '
				directory = raw_input('In which folder would you like to save the songs??\n')
				os.mkdir(directory)
				os.chdir(directory)
		else:
			os.mkdir(directory)
			os.chdir(directory)
		

readDir()
url = raw_input('Which url are you aiming at ?\n')
tmp = open('tempo.txt','w');
tmp.writelines(url)
tmp.close()
tmp = open('tempo.txt','r');
link = tmp.read()
os.system(" curl " + link +"| egrep -o 'http:.*All\.ram'  > final.txt  ")



infile =open('final.txt', 'r')
outfile = open('tmp.txt', 'w')

	

for line in infile:
	
	outfile = open('tmp.txt', 'w')
	key = line
	list = key.split("/")
	dir = list[6]
	outfile.writelines(key)
	outfile.close()
	open('tmp.txt','r')
	os.system("cat tmp.txt | xargs -n1 -i curl {} > links")
	os.system("wget -P %s -i links" %dir)

infile.close()
outfile.close()
os.remove(outfile.name)
os.remove('links')
os.remove(tmp.name)