Chinaunix首页 | 论坛 | 博客
  • 博客访问: 251497
  • 博文数量: 91
  • 博客积分: 4185
  • 博客等级: 上校
  • 技术积分: 855
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-29 16:18
文章分类

全部博文(91)

文章存档

2014年(3)

2013年(1)

2012年(8)

2011年(2)

2010年(5)

2009年(68)

2008年(4)

我的朋友

分类: Python/Ruby

2009-05-04 17:08:09

1. socket.error :
except socket.error as errobj:
          print('fpt error: %s can\'t download file %s' \
                    % errobj, filename)

2.ASCII码与字符的转换
chr(i) eg: chr(97) -> 'a'
ord(alpha) eg: ord('a') -> 97

3.subprocess中输入输出重定向到管道
from subprocess import Popen, PIPE, STDOUT

cmd = 'ls /etc/fstab /etc/non-existent-file'
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
output = p.stdout.read()
print output

4.datetime 对象的 utcnow()、now()、today()得到的时间都会精确到微秒。

5.捕获所有异常
try :
......
except Exception as ex :
print('Exception:', ex)

6.ftplib模块的使用
ftp rfc959
ftplib 与 rfc959 一起可以构建ftp客户端与服务器端
7.保留浮点数的n位小数
可以用round函数,round( x[, n]) ,对x保留四舍五入到n位小数。

8.捕获系统输出(字节流)并正确显示出来(解码)
这个问题的由来是由于这一段代码(在win上运行):
--------------------------------------------------------------
import sys
from subprocess import PIPE, Popen

code = sys.getfilesystemencoding()
args = 'copy /y a b'
exeCmd = Popen(args = args, stdin = PIPE, stdout = PIPE, \
    stderr = PIPE, shell = True)
output = exeCmd.communicate()[0].decode(code)
#error method: output = exeCmd.communicate()[0].decode()
print(output)
--------------------------------------------------------------
如果用注释中那行代码,则会抛出
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 4-5: invalid data
这样的异常,后来我就修改为上面这段正确的代码了,

现在这段代码可以正确运行了!

9、创建win文件快捷方式
    

and used the following code that created a directory shortcut on my T drive
named "test" that points to the "ftemp" directory (also on T):

import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()

Note that when I used "/" instead of "\\" in the pathnames the shortcut was
*not* created properly.

10、原来的Tkinter模块在python3.0中改为tkinter模块
原来的tkSimpleDialog和tkMessageBox模块,在python3.0是tkinter.simpledialog
和 tkinter.messagebox 类
11、list居然沒有clear()方法,除了用for remove之外還有沒有更好的方法?
    >>> a = [1,2,3]
    >>> id(a)
    33597760
    >>> del a[:]
    >>> a
    []
    >>> id(a)
    33597760
12、多进程编程
    import subprocess, multiprocessing
    import time
 
    pList = []
    for i in range(0, 1000) :
        cmd = subprocess.Popen(args = 'test.py ' + str(i), shell = True)
        pList.append(cmd)
    for i, p in enumerate(pList) :
        p.wait()
        print('process %d finished' % (i))
    print('main finished')
 
     在multiprocessing中使用subprocess要注意的问题
import os,subprocess,multiprocessing
def f():
        #p = subprocess.Popen(args = 'echo hello', stdout=subprocess.PIPE, \
        #        shell = True)
        p = subprocess.Popen(['test.py', 'hello'], stdout=subprocess.PIPE, \
                shell = True)
        out = p.communicate()
        print(repr(out))
pr = multiprocessing.Process(target=f)
pr.start()
 
    subprocess.Popen一句中,如果是调用python脚本则命令调用形式必需是以列表的形式调用,不然会
    出现如下错误:
wanneng@wanneng-desktop:~/workspace/test$ ./b.py
Fatal Python error: Py_Initialize: can't initialize sys standard
streams
Traceback (most recent call last):
  File "/usr/local/lib/python3.0/io.py", line 222, in open
    closefd)
  File "/usr/local/lib/python3.0/io.py", line 619, in __init__
    _fileio._FileIO.__init__(self, name, mode, closefd)
OSError: [Errno 9] Bad file descriptor
Aborted
(b'', None)
    如果是其它命令有时用args = "..."的形式调用也可以正确运行。

13、byte <=> str(python3.0)
    we looked at how to convert between strings of the str data type and strings of the bytes data type in the string class of . Another way that is a bit more straightforward is to simply call the function form of the target data type. So, to convert to str, call
str(, )
Similarly, you can make bytes from str with
bytes(, )
14、全局变量的定义
    globalvar.py
    s = None

    b.py
    import globalvar
    def prints()
        print(globalvar.s)

    a.py
    import b
    import globalvar
    globalvar.s = 'a.py'
    b.prints()

    运行a.py 会输出:a.py
    那么如果我们把所有的import globalvar都改成from globalvar import s,这些代码还能不能正常运行呢?答案是不能!如果改成from import后,会使得所有对s的修改成为局部的,也就是这样的s表现得与局部变量一样了,不再有全局的特性。

15 、反射与反省
    http://blog.csdn.net/lokibalder/archive/2008/12/06/3459722.aspx
    http://guoshiguan.javaeye.com/blog/308674
   
    a.py有类A,如果在a.py中使用__import__()又再次导入a模块,并从中得到类对象A,如果用print(aClassObj)会发现输出了两个。代码如下:
 

class A:
    def printf(self) :
        print('hello A')

class Factory :
    def getA(self) :
        classStr = 'A'
        module = 'a'
        moduleObj = __import__(module)
        #aClass = globals()[classStr]
        aClass = getattr(moduleObj, 'A')
        print(aClass)
        return aClass()

#print(globals())
factory = Factory()
aObj = factory.getA()
#aObj.printf()

    这种情况下应该使用global来得到A的类对象。
    通常在__import__(moduleName)之后,还要moduleObj = sys.modules[moduleName],这样才能得到带有多个层级的包,例如 a.b.c.d

16、类的静态变量,与静态方法

class A :
    i = 0
    def printf(self) :
        print(A.i)
        A.i = A.i + 1

    当其它模块使用该类时,所有的A实例对象都只一份i变量,这里的i变量也只有通过A.i的形式才能调用。
    如果printf(self)里没有self即def printf(),则这个方法就是A的静态方法,使用A.printf()来调用。

17、获取traceback内容
    http://blog.donews.com/limodou/archive/2004/07/09/40045.aspx

18、判断实例类型
    class A :
    aobj = A()
    isinstance(aobj, A) return True

19、日志模块里,所有自己所以创建的日志名都是从root来的,而logging.basicConfig也是对root进行设置,当设置了root的终端输出,再设置其它的日志处理器就会在屏幕上重复输出两次,所以如果用了其它的日志处理器在屏幕上输出就不要设置root。len(root.handlers)可以得到root有几个handler

20、日志handler的使用
如果要从logger中把某个handler给remove掉,并且以后也不会再用到这个handler,那么就要先把这个handler给关闭掉(如果有close方法的话),如果不关闭,很有可能造成打开过多的文件,比如fileHandler,过多的fileHandler就可能引起这种情况
    在linux中,可以从/proc/process_id/fd来查看进程打开了哪些文件
阅读(3472) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~