html tool

显示标签为“源码阅读”的博文。显示所有博文
显示标签为“源码阅读”的博文。显示所有博文

2014年7月22日星期二

goagent_local源码阅读_class Logging(type(sys))_II

 
      def __init__(self,*args,**kwargs):
        self.level = self.__class__.INFO //1
        self.__set_error_color = lambda: None
        self.__set_warning_color = lambda: None
        self.__set_debug_color = lambda: None
        self.__reset_color = lambda: None
        if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): //2
            if os.name == 'nt': //3
                import ctypes //5
                SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute //6
                GetStdHandle = ctypes.windll.kernel32.GetStdHandle //7
                self.__set_error_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x04)//8
                self.__set_warning_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x06) //9
                self.__set_debug_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x002) //10
                self.__reset_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x07) //11
            elif os.name == 'posix': //4
                self.__set_error_color = lambda: sys.stderr.write('\033[31m')//12     
                self.__set_warning_color = lambda: sys.stderr.write('\033[33m')
                self.__set_debug_color = lambda: sys.stderr.write('\033[32m')

                self.__reset_color = lambda: sys.stderr.write('\033[0m')  


12
sys.stderr.write
add:http://stackoverflow.com/questions/6195877/python-colour-printing-with-decorator-in-a-function
The simplest solution would be similar to what Pete suggest. Just print the escape codes before running the function to each of stderr and stdout. However, if both stderr and stdout feed the same terminal, as is usually the case, they will interfere
那就是在输出字符前直接定义颜色就可以了;
而颜色用的是ANSI的color的定义
add:http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
有详细的说明,这里的例子是ls下的看来linux在shell中直接就定义这样使用
]
这个_init__是对不同os下的日志打印颜色做定义用的,日志区分为:
error
warni
debug
reset

级别     

2014年7月15日星期二

goagent_local源码阅读_class Logging(type(sys))_I


def __init__(self,*args,**kwargs):
        self.level = self.__class__.INFO //1
        self.__set_error_color = lambda: None
        self.__set_warning_color = lambda: None
        self.__set_debug_color = lambda: None
        self.__reset_color = lambda: None
        if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty(): //2
            if os.name == 'nt': //3
                import ctypes //5
                SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute //6
                GetStdHandle = ctypes.windll.kernel32.GetStdHandle //7
                self.__set_error_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x04)//8
                self.__set_warning_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x06) //9
                self.__set_debug_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x002) //10
                self.__reset_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x07) //11
            elif os.name == 'posix': //4
                self.__set_error_color = lambda: sys.stderr.write('\033[31m')//12
                self.__set_warning_color = lambda: sys.stderr.write('\033[33m')
                self.__set_debug_color = lambda: sys.stderr.write('\033[32m')
                self.__reset_color = lambda: sys.stderr.write('\033[0m')

[popexizhi:
1.__class__ is the instance’s class ,        self.level = self.__class__.INFO 是引用类的全局变量INFO = 20
2.hasattr(sys.stderr, 'isatty') 检查sys.stderr.isatty是存在的,and sys.stderr.isatty()如果存在这个那就检查一下是否为tty设备
sys.stderr linux中错误的输出流,下面是help的说明
The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter’s standard input, output and error streams. See File Objects for complete documentation of file objects
这个是file objects中关于isatty的说明
file.isatty()
Return True if the file is connected to a tty(-like) device, else False.
Note
If a file-like object is not associated with a real file, this method should not  be implemented
go了一下tty文件: 应该是特殊的虚拟终端或端口设备文件的检查
http://oss.org.cn/kernel-book/ldd3/ch18.html
http://flykof.pixnet.net/blog/post/24277709-%5B%E8%BD%89%E8%BC%89%E6%95%B4%E7%90%86%5Dwhat-is-tty%3F
3.“nt”及windows系列的操作系统
4.'posix' 及unix类的操作系统
5.
import ctypes [help]
ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python

6. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute 的介绍
add:http://msdn.microsoft.com/en-us/library/ms686047(VS.85).aspx
Sets the attributes of characters written to the console screen buffer by the WriteFile or WriteConsole function, or echoed by the ReadFile or ReadConsolefunction. This function affects text written after the function call.
这个是windows的文本或控制台写入属性的设置函数c++的函数头如下:
Syntax
C++
BOOL WINAPI SetConsoleTextAttribute(
  _In_  HANDLE hConsoleOutput,
  _In_  WORD wAttributes
);

Parameters
hConsoleOutput [in] :A handle to the console screen buffer. The handle must have the GENERIC_READ access right. For more information, see Console Buffer Security and Access Rights.
wAttributes [in] :The character attributes.
地址中有详细的此函数的来源,返回值,参数等等内容,windows提供的内容

7. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
add:http://msdn.microsoft.com/en-us/library/ms683231(v=vs.85).aspx
Retrieves a handle to the specified standard device (standard input, standard output, or standard error).
原来windows也有input,output and error.之前在shell中使用以为只有linux做了相关区分呢,看来自己对win32的系统还真是不熟悉:)
看原文的参数说明
下面的-11使用的就是output [GetStdHandle(-11)]
STD_OUTPUT_HANDLE
(DWORD)-11   :The standard output device. Initially, this is the active console screen buffer, CONOUT$.
[8,9,10,11]
add:http://www.cnblogs.com/morewindows/archive/2011/09/19.html [这个是自己设置用c++的过程]
add:http://openexz.sinaapp.com/2011/02/17/%E8%BD%ACcc%E6%8E%A7%E5%88%B6%E5%8F%B0%E8%BE%93%E5%87%BA%E6%97%B6%E8%AE%BE%E7%BD%AE%E5%AD%97%E4%BD%93%E5%8F%8A%E8%83%8C%E6%99%AF%E9%A2%9C%E8%89%B2/[这个有详细的颜色定义]
这样翻译过来就是
8  error_color 定义背景色黑色 ,字体red[4]
9 warning_color定义背景色黑色,字体黄色[6]
10 debug_color 定义背景色黑色,字体绿色[2]
11 reset_color 定义背景色黑色,字体蓝色[1]
12[next]

       ]     

2014年6月3日星期二

goagent_local源码阅读_main()_II:os.chdir(os.path.dirname(os.path.abspath(__file__)))

os.chdir(os.path.dirname(os.path.abspath(__file__)))

  •        1.os.path.dirname()
    os.path.dirname(path)
    Return the directory name of pathname path. This is the first half of the pair returned by split(path).
    测试了一下,在windows中如果路径不用\\转义head,tail的分割会出现问题,参见如下lab结果
    >>> print os.path.dirname("F:\pc\work\个人中心\分析\1.txt")
    F:\pc\work\个人中心
    >>> print os.path.dirname("F:\\pc\\work\\个人中心\\分析\\1.txt")
    F:\pc\work\个人中心\分析
    >>> print os.path.dirname("D:\My Documents\AppScan\1.txt") #不包含中文
    D:\My Documents
    >>> print os.path.dirname("D:\\My Documents\\AppScan\\1.txt")
    D:\My Documents\AppScan
    • help 对 split()的解释为:
      os.path.split(path)
      Split the pathname path into a pair, (head,  tail) where tail is the last pathname component and head is everything leading up to that. The tail  part will never contain a slash; if path ends in a slash, tail  will be empty. If there is no slash in path, head  will be empty. If path is empty, both head and tail  are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In nearly all cases, join(head, tail) equals path  (the only exception being when there were multiple slashes separating head from tail).
      这样看来应该是用最后一个反斜杠来划分head,tail的,查一下源码看看如何实现的:
      • 先查到os,发现如下定义:
        - os.path is one of the modules posixpath, or ntpath
        再查posixpath.py 中如下:
        def split(p):
            """Split a pathname.  Returns tuple "(head, tail)" where "tail" is
            everything after the final slash.  Either part may be empty."""
            i = p.rfind('/') + 1
            head, tail = p[:i], p[i:]
            if head and head != '/'*len(head):
                head = head.rstrip('/')
            return head, tail
        help这个str.rfind()为:
        str.rfind(sub[, start[, end]])
        Return the highest index in the string where substring sub  is found, such that sub is contained within s[start,end]. Optional arguments start and end  are interpreted as in slice notation. Return -1  on failure
        实验了一下如下:
        >>> x="F:\pc\work\个人中心\分析\1.txt"
        >>> a=x.rfind("\\")
        >>> a=a+1
        >>> print x[:a]
        F:\pc\work\个人中心\
        >>> print x[a:]
        分析.txt

        ok了,像自己猜测的一样了,str.rfind()返回了最大的匹配位置,而 head, tail = p[:i], p[i:] 的写法就是用这个位置直接分割字符了,但是这个 if head and head != '/'*len(head): 应该是处理head为空,即当前目录的文件,问题是head != '/'*len(head) 是什么呢?[next]
        def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" i = p.rfind('/') + 1 head, tail = p[:i], p[i:] if head and head != '/'*len(head): head = head.rstrip('/') return head, tail
    2.os.chdir()  

2014年2月19日星期三

python中的os.path.islink与os.readlink在2.7版本中的一些问题

源码:
global __file__
__file__=os.path.abspath(__file__)
if os.path.islink(__file__):
__file__=getattr(os,'readlink',lambda x:x)(__file__)

问题:
1.os.path.islink的作用是什么?
2.os.readlink 为什么有可能不存在呢?要使用getattr来返回这个os模块的操作,对没有定义这个操作的情况是什么呢?

对于1.查help中为
os.path.islink(path)
Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported.
新问题:a symbolic link是什么文件呢?是快捷方式吗?有不支持快捷方式的os?
查到的结果中http://stackoverflow.com/questions/15258506/os-path-islink-on-windows-with-python中有了详细的解释,原来这个方法本身在

2.7版本之后做过bug修改的,原文说:
One of those features is handling NTFS symlinks. That functionality was added in 3.2 in late 2010. (See the 3.2, 3.1, and 2.7

source for details.)
上面源码中是用的是python27版本
查了这个bug的官方描述为http://bugs.python.org/issue13143

ok现在的问题是NTFS symlinks 与 symbolic link 的关系,子集?还有就是他们到底是what?
在这个http://hi.baidu.com/xiayang/item/9f29e7112f5433eb9913d622 中终于有了答案,原文如下:
"NTFS同样具有Linux早就使用的Hard Link和Soft Link功能...
Soft Link在微软的NTFS里头有另一个名 字:symbolic link(符号链接)。它类似于Windows里头常用的.lnk快捷方式,但是微软也同样给出了限

制:symbolic link只能应用于文件夹(包括卷),但可以跨分区使用(可以在D盘生成一个指向C盘某文件夹的symbolic link)。如 果需要创建文

件的symbolic link,那就请使用.lnk吧。
而文件夹的symbolic link效果和.lnk差不 多,symbolic link本身是一个文件,用户一旦访问symbolic link的话就会自动跳转(Reparse)到目标

文件夹,不过 和.lnk不同的是,symbolic link是底层文件系统里头实现,对用户和程序透明——例如,文件夹B是文件夹A的symbolic link, 那

么程序访问B时就和访问A完全一样,就好像A里头的全部东西都改了路径到B下面了。不过相应的,如果你删除symbolic link(文件夹B)里头 的某

个文件,文件夹A里头相应的文件也会被删除的。2k/XP的Explorer似乎也对symbolic link支持不足,删除 symbolic link本身好像也会删除A……

symbolic link有什么用?如果你的系统盘满了,或者空间不足以让某些程序 运行时,就可以把一些在系统盘里头的文件夹移动到其他分区,然后

制造一个symbolic link,这样既可以腾出空间,也可以让其他程序不至于出错。 另外由于它基于NTFS文件系统,因此在一个操作系统生成的

symbolic link也同样能被另一个操作系统识别。

虽然微软没有推广 symbolic link,但是其实在2000已经开始有使用symbolic link了。
如果我们加载一个NTFS卷/分区,磁盘管理器会 提示盘符或者是否装载到某个NTFS文件夹,选择后者其实就是生成一个指向该卷/分区的symbolic

link "

wiki中给出的解释更为详细(symbolic_link http://en.wikipedia.org/wiki/Symbolic_link)

这样if os.path.islink(__file__)就是判断给出的__file__如果是symbolic link地址的话要处理一下的意思,处理成什么呢?猜想一下啊,应该

是改写为真实的原始地址吧?!


2.
首先getattr是个很棒的自省函数(参见http://woodpecker.org.cn/diveintopython/power_of_introspection/getattr.html),但问题是在这里

是os.readlink 不支持者但依然使islink为true的会是谁呢?

这次查询help直接得出结果
Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative

pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result).

Changed in version 2.6: If the path is a Unicode object the result will also be a Unicode object.

Availability: Unix.

这个os.readlink 是unix专用的,那么1中islink判断的windows中的ntfs下的symbolic link就使用 lambda x:x 了 ok,以上help用的都是2.7的官

方帮助,
查询了一下python3.2的如下
Availability: Unix, Windows

Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links.

ok,自己查看的源程序指定版本是python27了,一直没太留心python3的内容,改进东西不少啊:)