python编程

eclipse 安装pydev插件

http://pydev.org/updates


支持中文

文件开头 #-*- coding: cp936 -*-

测试open中文路径可以


问题 eclipse pydev MalformedByteSequenceException

解决:把eclipse放到没有中文的路径中


环境部署

在python根目录下创建一个bat文件,内容如下,用于快速设置环境(不用修改PATH路径)

PATH=%PATH%;C:\Python27
cmd.exe


py2exe打包工具使用

1.下载py2exe并安装 http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/

2.编译窗口程序:指定要编译的py文件,然后输入python bin_setup.py

------------------------------------------bin_setup.py-------------------------------------------------------

# -*- coding: utf-8 -*-

__author__ = 'lxd'

from distutils.core import setup  
import py2exe  
import sys

# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
    sys.argv.append("py2exe")
    sys.argv.append("-q")

INCLUDES = []

MANIFEST_TEMPLATE = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity
    version="5.0.0.0"
    processorArchitecture="x86"
    name="%(prog)s"
    type="win32"
  />
  <description>%(prog)s</description>
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel
            level="asInvoker"
            uiAccess="false">
        </requestedExecutionLevel>
      </requestedPrivileges>
    </security>
  </trustInfo>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity
            type="win32"
            name="Microsoft.VC90.CRT"
            version="9.0.21022.8"
            processorArchitecture="x86"
            publicKeyToken="1fc8b3b9a1e18e3b">
      </assemblyIdentity>
    </dependentAssembly>
  </dependency>
  <dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="X86"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
  </dependency>
</assembly>
"""
RT_MANIFEST = 24

options = {"py2exe" :
    {"compressed" : 1,
     "optimize" : 2,
     "bundle_files" : 2,
     "includes" : INCLUDES,
     "excludes" : ["Tkinter",],
     "dll_excludes": [ "MSVCP90.dll", "mswsock.dll", "powrprof.dll"] }}

windows = [{"script": "bin.py",
      "icon_resources": [(1, "bin.ico")],
      "other_resources" : [(RT_MANIFEST, 1,
                        MANIFEST_TEMPLATE % dict(prog="MyAppName"))],
      }]

setup(name = "MyApp",
      version = "1.0",
      description = "Description of the app",
      author = "Author Name",
      author_email ="author@project.com",
      maintainer = "Maintainer Name",
      maintainer_email = "you@project.com",
      license = "wxWindows Licence",
      url = "http://projecthomepage.com",

      #data_files = ["MSVCR90.dll", "gdiplus.dll"],
      #data_files=[("img",[r"d:\test\1.gif",r"d:\test\2.gif"]),("xml",[r"d:\test\1.xml",r"d:\test\2.xml"])])
      #zipfile=None,
      options = options,
      windows = windows,
      )

3.编译控制台程序:指定要编译的py文件,然后输入python mysetup.py py2exe

-------------------------mysetup.py-------------------------

from distutils.core import setup
import py2exe

setup(console=['hello.py'])

注意:python 2.6需要做如下操作

注释掉build_exe.py中的#import sets
把里面的sets.Set替换为set  ,就是使用默认的set类


ubuntu安装wxpython

sudo apt-get install python-wxtools

列表,字典使用

a=[1,2]
b=[3,4,1]
c=a*8

c=[a]*4
print c
c=a+b
print c
a=[5,6]
print a

del a[0]


a={1:'a',2:'b',3:'c'}
print a.has_key(1)
print a.keys()
print a.values()


lambda表达式使用

f1=lambda x:x*x
f2=lambda x,y:x+y
print f1(8)
action,args=f1,(8,)
action,args=f2,(1,2)
print apply(action,args)

funclist=[(f1,(4,)),(f2,(2,3))]
for (func,arg) in funclist:
    print apply(func,arg)


python调用c

随便写一个win32dll

#-*- coding: cp936 -*-

from ctypes import *
libtest=cdll.LoadLibrary("G:/workspace/python_demo/src/testdll/Debug/testdll.dll")
print libtest.add(2,3)


调用win32

from ctypes import *
handle = c_int
handle=windll.user32.FindWindowA(None,"Program Manager")
print hex(handle)

outstr=create_string_buffer(100)

print sizeof(outstr),repr(outstr.raw)
windll.user32.GetWindowTextA(handle,outstr,100)
print outstr.value


载入标准库dll

#================================for windows=====================================

libc=CDLL("MSVCRT.DLL")

#例子

strchr=libc.strchr
strchr.argtypes=[c_char_p,c_char]
strchr.restype=c_char_p
print strchr("abcdef", "d" )

#byref可以传引用(相当于&)

#结构体
class POINT(Structure):
    _fields_=[("x",c_int),
              ("y",c_int)]
point =POINT(10,20)    
print point.x,point.y
print POINT.x,POINT.y

#Bit

class Int(Structure):
    _fields_ = [("first_16", c_int, 16),
                    ("second_16", c_int, 16)]
    
aaaaa=Int()
aaaaa.first_16=0x12
print hex(aaaaa.first_16)
aaaaa.first_16&=0xf8
print hex(aaaaa.first_16)

#数组
class MyArray(Structure):
    _fields_ = [("a", c_int),
                 ("b", c_float),
                 ("point_array", POINT * 4)]
print len(MyArray().point_array)

#具体看http://docs.python.org/library/ctypes.html

#===================================for linux=======================================

libc=CDLL("libc.so.6")


编译代码,并解释运行

exec 代码

例如:

exec "import string" 

modname=__import__(modname) #运行多次的话,使用这种方式


重载运算符

__init__

__del__

__add__

__or__

__repr__

__call__

__getattr__

__getitem__

__setitem__

__getslice__

__len__

__cmp__

__radd__


模板方法

class Super:
def delegate(self):
self.action()

class Son(Super):
def action(self):
print 'In son'


查看所有属性元素

a.__dict__

dir(a) #显示对象元素列表

a.__class__.__name__ #类名

a.__class__.__bases__#父类


设计模式

工厂

def factory(aClass,*args,**kwargs):
return apply(aClass,args,kwargs)


当前的异常名和数据

sys.exc_type

sys.exc_value


常用函数

ord('a') #转十进制数

chr(97)#转char

map(chr,(83,112,97)) #转多个

str(string)

list("tomato")

tuple("tomato")

os.getcwd()

os.listdir('path')

os.rename('filename')

os.remove('ddd')

os.unlink('ddd')

os.mkdir('ddd')

os.rmdir('ddd')

os.curdir

os.pardir

os.seq

os.pathseq

os.path.split("c:/dfdf/dfd/a.doc")

os.path.join("c:/dfdf/dfd/","a.doc")

os.path.normpath("c:\dfd")

shutil.copyfile("c:/1.txt","c:/2.txt")

shutil.copymode(src,dest)

shutil.copystat(src,dest)

shutil.copytree(src,dest)

shutil.rmtree(path)

urllib.urlopen

urllib.urlretrieve

urllib.unquote('this%20%26%20that')   'this & that'

urllib.urlencode()  #转为url编码

urllib.urlparse 

urllib.urlunparse 

urllib.urljoin


其他lib库

htmllib

xmllib

base64

...


hasattr, getattr, setattr, delattr


对象的浅,深拷贝
import copy
copy.copy
copy.deepcopy


python类的私有属性
_data #伪私有
__data #私有,不能直接访问(其实被改成'_类名__data'了)


使用UserList,UserDict模块
from UserList import UserList
class Statck(UserList):
push = UserList.append
def pop(self):
item=self[-1]
del self[-1]
return item


判读是否含有某属性或方法
hasattr(obj,"pop")


类似Java,Net使用接口
class Interface:
    def doadd(self,a,b):
        raise AssertionError,"doadd not implement"
    def dosub(self,a,b):
        raise AssertionError,"dosub not implement"       
        
class B(Interface):
    def doadd(self,a,b):
        print "add=",a+b
    def dosub(self,a,b):
        print "sub",a-b
b=B()  
b.doadd(2,3)
b.dosub(2,4)


Linux下服务的守护进程

#!/usr/bin/env python
import os, sys, time

while True:
    time.sleep(3)
    try:
        ret = os.popen('ps -C nginx -o pid,cmd').readlines()
        if len(ret) < 2:
            print "nginx process killed, restarting service in 3 seconds."
            time.sleep(3)
            os.system("service nginx restart")
    except:
        print "Error", sys.exc_info()[1]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值