Python 列出路径中的所有目录并将信息保存到文本文件中

####################################################
##
##  Prints a dir structure to a text file
##
##  Usage : python printdir.py [path ala z:/mypath or /mypath/foo
##
####################################################

import os, sys

dir = sys.argv[1]
outName = 'dirpaths.txt'
f = open(outName,'w')

# write initial dir for reference
f.write (dir + '\n')

count = 0

for item in os.walk(dir):
    count = count + 1
    item = item[0].replace('\\','/')
    curPath = item.split('/')
    if count == 1:
        curPath = item
    else:
        curPath = '\t' * (len(curPath)-1) + curPath[len(curPath)-1]
    
    f.write(curPath + '\n')
    print curPath
  

f.close
if os.path.exists(outName) :
    print 'File saved to: %s' % (outName)

Python Python中类继承和方法重写的示例

#!/usr/bin/env python

class man(object):
    
    # name of the man
    name = ""
    
    def __init__(self, P_name):
        """ Class constructor """
        self.name = P_name
        print("Here comes " + self.name)
        
    def talk(self, P_message):        
        print(self.name + " says: '" + P_message + "'")        
        
    def walk(self):
        """ This let an instance of a man to walk """
        print(self.name + " walks")

# This class inherits from Man class
# A superman has all the powers of a man (A.K.A. Methods and Properties in our case ;-)
class superman(man):
    
    # Name of his secret identity
    secret_identity = ""
    
    def __init__(self, P_name, P_secret_identity):
        """ Class constructor that overrides its parent class constructor"""
        # Invokes the class constructor of the parent class #
        super(superman, self).__init__(P_name)
        # Now let's add a secret identity
        self.secret_identity = P_secret_identity
        print("...but his secret identity is '" + self.secret_identity + "' and he's a super-hero!")
    
    def walk(self, P_super_speed = False):
        # Overrides the normal walk, because a superman can walk at a normal
        # pace or run at the speed of light!
        if (not P_super_speed): super(superman, self).walk()
        else: print(self.secret_identity + " run at the speed of light")
        
    def fly(self):
        """ This let an instance of a superman to fly """
        # No man can do this!
        print(self.secret_identity + " fly up in the sky")
        
    def x_ray(self):
        """ This let an instance of a superman to use his x-ray vision """
        # No man can do this!
        print(self.secret_identity + " uses his x-ray vision")
        

# Declare some instances of man and superman
lois = man("Lois Lane")
jimmy = man("Jimmy Olsen")
clark = superman("Clark Kent", "Superman")

# Let's puth them into action!

print("\n--> Let's see what a man can do:\n")
jimmy.walk()
lois.talk("Oh no, we're in danger!")

print("\n--> Let's see what a superman can do:\n")
clark.walk()
clark.talk("This is a job for SUPERMAN!")
clark.walk(True)
clark.fly()
clark.x_ray()

Python 从网站中提取网址

import re
import urllib.request

# Retrieves URLs from the HTML source code of a website
def extractUrlsFrom(url, unique=True, sort=True, restrictToTld=None):
    # Prepend "www." if not present
    if url[0:4] != "www.":
        url = "".join(["www.",url])
    # Open a connection
    with urllib.request.urlopen("http://" + url) as h:
        # Grab the headers
        headers = h.info()
        # Default charset
        charset = "ISO-8859-1"
        # If a charset is in the headers then override the default
        for i in headers:
            match = re.search(r"charset=([\w\-]+)", headers[i], re.I)
            if match != None:
                charset = match.group(1).lower()
                break
        # Grab and decode the source code
        source = h.read().decode(charset)
        # Find all URLs in the source code
        matches = re.findall(r"http\:\/\/(www.)?([a-z0-9\-\.]+\.[a-z]{2,6})\b", source, re.I)
        # Abort if no URLs were found
        if matches == None:
            return None
        # Collect URLs
        collection = []
        # Go over URLs one by one
        for url in matches:
            url = url[1].lower()
            # If there are more than one dot then the URL contains
            # subdomain(s), which we remove
            if url.count(".") > 1:
                temp = url.split(".")
                tld = temp.pop()
                url = "".join([temp.pop(),".",tld])
            # Restrict to TLD if one is set
            if restrictToTld:
                tld = url.split(".").pop()
                if tld != restrictToTld:
                    continue
            # If only unique URLs should be returned
            if unique:
                if url not in collection:
                    collection.append(url)
            # Otherwise just add the URL to the collection
            else:
                collection.append(url)
        # Done
        return sorted(collection) if sort else collection

# Test
url = "snipplr.com"
print("From:", url)
for x in extractUrlsFrom(url):
    print("-", x)

Python 以编程方式创建目录

import sys
import os


def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)


def main():
	for x in range(150):
                # change this as needed
		filename = "/Users/mac/Desktop/temp/" + str(x+1) + "/"
		ensure_dir(filename)


if __name__ == '__main__':
	main()

Python VIRTUALENV

Install with:
easy_install virtualenv

To create and activate one virtual environment with the name "myvirtenv" use:
virtualenv myvirtenv
cd myvirtenv
source bin/active

To leave this environment use:
deactivate

Python 使用ctypes的Python mini Win32 Api用法:D

from ctypes import *

class Win32api():
   def __init__(self):
       self.SetWindowText = windll.user32.SetWindowTextA #msdn for what dll to use
       self.FindWindow = windll.user32.FindWindowA # i dont use unicode(maybe i should?)
   
   def String(self,s):
       return c_char_p(s)

   def Int(self,i):
       return c_int(i)

   def Long(self,l):
       return c_long(l)

#small test open command prompt type title lol
test = Win32api()

#none in python is == NULL in C(more or less)
ret = test.FindWindow(None,test.String("lol"))

#ret holds the window handle HWND(which is really a long/int)
test.SetWindowText(ret,test.String("Command Prompt :D"))

print("done")
#just for good measure!

Python python中的Qt GUI应用程序与pyqt(子类化pyuic4生成的文件)

import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from <REPLACE_BY_PYUI_DESIGN> import <REPLACE_BY_WINDOW_CLASS_IN_PYUI_DESIGN>

class MainWindow(QMainWindow, <REPLACE_BY_WINDOW_CLASS_IN_PYUI_DESIGN>):

    # custom slot
    def mymethod(self):
        self.textFieldExample.setText('Hello World')
        self.textFieldExample.clear()

    def __init__(self):
        QMainWindow.__init__(self)
      
       # set up User Interface (widgets, layout...)
        self.setupUi(self)
        # custom slots connections
        QObject.connect(self.pushButton,SIGNAL("released()"),self.mymethod) # signal/slot connection
    
# Main entry to program.  Sets up the main app and create a new window.
def main(argv):
   
    # create Qt application
    app = QApplication(argv,True)
 
    # create main window
    wnd = MainWindow() # classname
    wnd.show()
    
    # Connect signal for app finish
    app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))
    
    # Start the app up
    sys.exit(app.exec_())
 
if __name__ == "__main__":
    main(sys.argv)

Python 为django创建模型的函数

from django.forms import ModelForm


def create_modelform(model_, module=None):
    class _modelform(ModelForm):
        class Meta:
            model = model_

    if module:
        _modelform.__module__ = module
    else:
        _modelform.__module__ = model_.__module__
    _modelform.__name__ = '%sForm' % model_.__name__
    return _modelform

Python 字计数器

# BY: AMIR NAGHAVI
# amirenzo10@gmail.com
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>

"""
this two programm go through lines among text or html files
and count number of repeating the given word
"""
class find(object):
    def __init__(self,path,word):
        self.p=path  #-----text file path
        self.w=word  #-----the word to look for repeating
    def start(self):
        f=open(self.p)

        chrcount=0     # character counter ;indicates and separates words
        numofrep=0    # number of word that would repeat

        length=len(self.w)

        for line in f:
            lineflag=False  #--to printing line once if it has the give word more than once  <--
            for j in line:                                                               #      \
                if j==self.w[chrcount] and chrcount<=length:                             #       \
                    chrcount+=1                                                          #        \
                    if chrcount==length:  #--finding the word                                     |
                        chrcount=0                                                       #        | 
                        numofrep+=1                                                      #        |
                        if lineflag!=True:  # if in line are more than one "word" print line once-|
                            print line
                            lineflag=True
                else:
                    chrcount=0
        print 'Number of repeat: ',numofrep
        



# ------------------------------- searvhing through web pages
class word_counter_in_web(find):
    def __init__(self,add,word):
        self.add=add
        self.w=word
    def start(self):
        from urllib import urlopen
        #url=urlopen(self.add)

        length=len(self.w)
        chrcount=0
        numofrep=0

        for line in self.add:
            lineflag=False
            for j in line:
                if j==self.w[chrcount] and chrcount<=length:
                    chrcount+=1
                    if chrcount==length:
                        numofrep+=1
                        chrcount=0
                        if lineflag!=True:
                            lineflag=True
                            
        #print 'repeat number for %s is %d' %(self.w,numofrep)
        return numofrep
# -------------------------------------
# RUN:
if __name__=="__main__":
    find('D:\cpuz-readme.txt','cpu').start()
    #print word_counter_in_web('http://www.python.org','python').start()

Python 伟大的Python装饰器示例

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2) :

    print "I make decorators ! And I accept arguments:", decorator_arg1, decorator_arg2

    def my_decorator(func) :
        # The hability to pass arguments here is a gift from closures.
        # If you are not confortable with closures, you can assume it's ok,
        # or read : http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2

        # Don't confuse decorator arguments and function arguments !
        def wrapped(function_arg1, function_arg2) :
            print "I am the wrapper arround the decorated function.",\
                  "\nI can access all the variables",\
                  "\n\t- from the decorator:", decorator_arg1, decorator_arg2,\
                  "\n\t- from the function call:", function_arg1, function_arg2,\
                  "\nThen I can pass them to the decorated function"
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2) :
    print "I am the decorated function and only knows about my arguments :",\
          function_arg1, function_arg2

decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators ! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper arround the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Sheldon 
#   - from the function call: Rajesh Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments : Rajesh Howard