BEEN
life‘s short
日历
五月 | ||||||
---|---|---|---|---|---|---|
日 | 一 | 二 | 三 | 四 | 五 | 六 |
27 | 28 | 29 | 30 | 1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
最新评论
最新留言
链接
python 执行过程
2014年2月23日 16:17 | Comments(4) | Category:python | Tags:
参考资料
Dive into python
在Dive into python第五章中有一个提取MP3信息的脚本,不是很理解现在整理一下思路
"""Framework for getting filetype-specific metadata. Instantiate appropriate class with filename. Returned object acts like a dictionary, with key-value pairs for each piece of metadata. import fileinfo info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3") print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()]) Or use listDirectory function to get info on all files in a directory. for info in fileinfo.listDirectory("/music/ap/", [".mp3"]): ... Framework can be extended by adding classes for particular file types, e.g. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for parsing its files appropriately; see MP3FileInfo for example. This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark@diveintopython.org)" __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2001 Mark Pilgrim" __license__ = "Python" import os import sys from UserDict import UserDict def stripnulls(data): "strip whitespace and nulls" return data.replace("\00", " ").strip() class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)} def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == "name" and item: self.__parse(item) FileInfo.__setitem__(self, key, item) def listDirectory(directory, fileExtList): "get list of file info objects for files of particular extensions" fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [os.path.join(directory, f) for f in fileList \ if os.path.splitext(f)[1] in fileExtList] def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) and getattr(module, subclass) or FileInfox return [getFileInfoClass(f)(f) for f in fileList] if __name__ == "__main__": for info in listDirectory("/home/been/Desktop/", [".mp3"]): print "\n".join(["%s=%s" % (k, v) for k, v in info.items()]) print
用户执行代码从这里开始
if __name__ == "__main__": for info in listDirectory("/home/been/Desktop/", [".mp3"]):
一个for循环代码跳到了自定义的function上
def listDirectory(directory, fileExtList): "get list of file info objects for files of particular extensions" fileList = [os.path.normcase(f) for f in os.listdir(directory)] """这里返回在目录directory下的所有文件,文件夹的小写名称到fielList""" fileList = [os.path.join(directory, f) for f in fileList \ if os.path.splitext(f)[1] in fileExtList] """这里返回的是所有带地址的mp3格式的文件名,如/home/been/Desktop/wake me up.mp3""" def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] """subclass 的内容是MP3FileInfo""" return hasattr(module, subclass) and getattr(module, subclass) or FileInfox """hastter()和getatter()是检查subclass这个模块是否可用,是就返回hasatter()否则返回FileInfo 不过这里不仅仅是返回那么简单,同时还是调用了MP3FileInfo这个模块""" return [getFileInfoClass(f)(f) for f in fileList]
python执行代码到这里
class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)}
MP3FileInfo从FileInfo中继承了它的方法,代码又跑到了这里
class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename
同样FileInfo又从UserDict中继承了它的方法,UserDict是一个python自定义的class,用来创建字典的类。
可以用pydoc UserDict查看它的方法和属性。可以在/usr/lib/python2.7/UserDict.py 查看源代码
这部分代码生成了一个字典{filename:none}
接着代码回到了这里
class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)} def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == "name" and item: self.__parse(item) FileInfo.__setitem__(self, key, item)
在这里代码首先在__setitem__执行,疑问出来了书上说__setitem__是被MP3FileInfo覆盖的,但是__setitem__()却要和父类UserDict中的__setitem__()的参数的个数要一样。下面这两个是为了解决临界问题
当首次执行__setitem__时key为not defined,item在__parse已经创建。理解if这一句需要知道== and的优先顺序,这一句的意思是:如果key=="name"则执行self.__parse(item)否则执行File~。
因为FileInfo没有__setitem__类,因此需要到父类UserDict中去找。到这里所有的信息都存在了FileInfo字典中。
最后的代码
if __name__ == "__main__": for info in listDirectory("/home/been/Desktop/", [".mp3"]): print "\n".join(["%s=%s" % (k, v) for k, v in info.items()]) print
for语句这里的info in ListDirectory(),相当于info=MP3FileInfo(),所以info有info.items()属性
后记:把博文写出来的确是对代码理解透彻了很多,因为只学过c,对类这种编程思想跟本没有了解过,一直在纠结干嘛要创建字典,是怎么通过类给字典里的key:value赋值,是怎么提取里面的元素的
补充python运算符的优先顺序:从上往下递增
运算符 | 描述 |
---|---|
lambda | Lambda表达式 |
or | 布尔“或” |
and | 布尔“与” |
not x | 布尔“非” |
in,not in | 成员测试 |
is,is not | 同一性测试 |
<,<=,>,>=,!=,== | 比较 |
| | 按位或 |
^ | 按位异或 |
& | 按位与 |
<<,>> | 移位 |
+,- | 加法与减法 |
*,/,% | 乘法、除法与取余 |
+x,-x | 正负号 |
~x | 按位翻转 |
** | 指数 |
x.attribute | 属性参考 |
x[index] | 下标 |
x[index:index] | 寻址段 |
f(arguments...) | 函数调用 |
(experession,...) | 绑定或元组显示 |
[expression,...] | 列表显示 |
{key:datum,...} | 字典显示 |
'expression,...' | 字符串转换 |
代码执行过程
2014年2月23日 13:26 | Comments(1) | Category:python | Tags:
参考资料:
Dive into python
Dive into python 第五章中的有一个脚本,是提取MP3文件中的信息的。一直很不理解,现在希望整理一下思路
"""Framework for getting filetype-specific metadata. Instantiate appropriate class with filename. Returned object acts like a dictionary, with key-value pairs for each piece of metadata. import fileinfo info = fileinfo.MP3FileInfo("/music/ap/mahadeva.mp3") print "\\n".join(["%s=%s" % (k, v) for k, v in info.items()]) Or use listDirectory function to get info on all files in a directory. for info in fileinfo.listDirectory("/music/ap/", [".mp3"]): ... Framework can be extended by adding classes for particular file types, e.g. HTMLFileInfo, MPGFileInfo, DOCFileInfo. Each class is completely responsible for parsing its files appropriately; see MP3FileInfo for example. This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark@diveintopython.org)" __version__ = "$Revision: 1.3 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2001 Mark Pilgrim" __license__ = "Python" import os import sys from UserDict import UserDict def stripnulls(data): "strip whitespace and nulls" return data.replace("\00", " ").strip() class FileInfo(UserDict): "store file metadata" def __init__(self, filename=None): UserDict.__init__(self) self["name"] = filename class MP3FileInfo(FileInfo): "store ID3v1.0 MP3 tags" tagDataMap = {"title" : ( 3, 33, stripnulls), "artist" : ( 33, 63, stripnulls), "album" : ( 63, 93, stripnulls), "year" : ( 93, 97, stripnulls), "comment" : ( 97, 126, stripnulls), "genre" : (127, 128, ord)} def __parse(self, filename): "parse ID3v1.0 tags from MP3 file" self.clear() try: fsock = open(filename, "rb", 0) try: fsock.seek(-128, 2) tagdata = fsock.read(128) finally: fsock.close() if tagdata[:3] == 'TAG': for tag, (start, end, parseFunc) in self.tagDataMap.items(): self[tag] = parseFunc(tagdata[start:end]) except IOError: pass def __setitem__(self, key, item): if key == "name" and item: self.__parse(item) FileInfo.__setitem__(self, key, item) def listDirectory(directory, fileExtList): "get list of file info objects for files of particular extensions" fileList = [os.path.normcase(f) for f in os.listdir(directory)] fileList = [os.path.join(directory, f) for f in fileList \ if os.path.splitext(f)[1] in fileExtList] def getFileInfoClass(filename, module=sys.modules[FileInfo.__module__]): "get file info class from filename extension" subclass = "%sFileInfo" % os.path.splitext(filename)[1].upper()[1:] return hasattr(module, subclass) and getattr(module, subclass) or FileInfox return [getFileInfoClass(f)(f) for f in fileList]
if __name__ == "__main__": for info in listDirectory("/home/been/Desktop/", [".mp3"]):
print "\n".join(["%s=%s" % (k, v) for k, v in info.items()]) print
用户执行脚本,到达这里
can't disable telnet please help~~
2014年2月09日 01:14 | Comments(0) | Category:linux | Tags:
参考资料
ubuntu系统在默认情况下是没有启动telent服务的,需要自行配置
1.安装启动基础服务
sudo apt-get install xinetd
2.配置基础文件,在/etc/xinet.conf加入如下几行
# Simple configuration file for xinetd
#
# Some defaults, and include /etc/xinetd.d/
defaults
{
# Please note that you need a log_type line to be able to use log_on_success
# and log_on_failure. The default is the following :
# log_type = SYSLOG daemon info
instances = 60
log_type = SYSLOG authpriv
log_on_success = HOST PID
log_on_failure = HOST
cps = 25 30
}
3.安装telent客户端
sudo apt-get install telnet
4.配置telent文件,nano /etc/xinetd.d/telnet,在此目录下没有telent文件的自己touch
# default: on
# description: The telnet server serves telnet sessions; it uses
# unencrypted username/password pairs for authentication.
service telnet
{
disable = no
flags = REUSE
socket_type = stream
wait = no
user = root
server = /usr/sbin/in.telnetd
log_on_failure += USERID
}
更高安全要求配置
only_from = 192.168.120.0/24 #Only users in 192.168.120.0 can access to
only_from = .bob.com #allow access from bob.com
no_access = 192.168.120.{101,105} #not allow access from the two IP.
access_times = 8:00-9:00 20:00-21:00 #allow access in the two times
5.重启xinet服务
sudo /etc/init.d/xinetd restart
6.关闭telent服务,网上的教程是这样做的,但是我却不成功,求搭救~~
把/etc/xinetd.d/telnet 文件的 disable=no 改为yes
重启xinetd服务 sudo /etc/init.d/xinetd restart
> ps:重启xinetd服务 service xinetd restart 也可以,不过我的ubuntu不知道为什么,用tab能调出xinetd但是执行命令却是
stop: Unknown job: xinetd
start: Unknown job: xinetd
>ps 网上的重启xinetd服务是 sudo /etc/rc.d/init.d/xinetd restart 但是我/etc下没有rc.d 不过有rc0~6.d,不知道这个有没有关系呢
shell 基础
2013年12月26日 20:44 | Comments(0) | Category:linux | Tags:
参考资料 :UNIX和shell程序设计权威教程 清华大学出版社
鸟哥的私房菜
1.验证当前shell
echo $0
2.重定向
类型 | Korn shell or Bash shell |
输入 | 0<file1 |
输出 | 1>>file1(追加) or 1>|file1(覆盖) |
错误输入 | 2>>file1(追加形式) or 2>|file2(覆盖形式) |
输出错误(不同文件) | 1> file1 2>file2 |
输出错误(同一个文件) | 1>file1 2&1 |
重定向到垃圾桶 /dev/null
3.管道
注意管道的左边命令必须能够发送数据至标准输出,右端命令必须能从标准输入接收数据
方式 | 结果 |
$(variable#key) | 从变量的开头删除一直到key之后 |
$(variable##key) | 从变量的开头删除最长的字符串一直到key之后 |
$(variable%key) | 从变量的尾部开始删除一直到key之前 |
$(variable%%key) | 从变量的尾部开始删除最长的字符串一知道key之前 |
$(varible/old_k/new_key) |
用new_key替换第一个符合的old_k |
$(varible//old_key/new_key) | 用new_key替换所有的old_k |
grep
2013年12月25日 15:56 | Comments(1) | Category:linux | Tags:
The useful options of grep,egrep,fgrep
-i, Ignore case distinctions in both the patten and files
-v Invert the sense of matching,to selsect non-matching lines
-c Suppress normal output;instead print a count of matching line
-n Prefix each line of output with the 1-based line number
正则表达式
2013年12月22日 23:27 | Comments(0) | Category:linux | Tags:
参考书籍:unix和shell程序设计权威指南 清华出版社
一、原子
点:. 匹配任意ACII字符
类:[]匹配方括号内任意一个字符
注:方括号内使用转义字符\,非运算符^
[A-Za-z]:任意字符
锚:^ : 行首
$ :行尾
\< :单词词首
\> :单词词尾
注:锚和原子经常结合一起使用,如^Q表示已Q开头的一个字符串
向后引用
重新使用在一个正则表达式定义过的规则,不过这是有要求的,规则必须出现在()中,/1调用第一个括号里的规则、/2 /3……以此类推。加入多个括号嵌套使用系统会自动给最先出现的'('分配.
二、正则表达式的运算符
序列运算符:序列算符为空,它的含义是:如果有原子系列出现在正则表达式中则表示在原子之间有一个不可见的序列运算符
注:[0-9][0-9]任意数字
替换:| 相当于是 A or B,AB中的任意一个
重复:\{m,n\}
说明:最多n个可以是0到n \{,n\}
最少n个必须比n个多\{n,\}
精确n个\{n\}
缩写形式运算符:?匹配前面的原子0到1次
+匹配前面的原子1到多次
*匹配前面的原子0到多次
组运算符:()相当于四则运算里的括号,被括起来的部分先进行运算
注:*(?=xxxx)匹配*的右边必须是xxxx *(?>=xxxx)匹配的左边必须是xxxx
\r,\n | carriage return,newline character |
\t | Tabs |
\d | Any digit character,any ont of 0~9 |
\w | any alpha,numeric,underline |
\s | Any one of space,tab,newline, or\n |
. | Any character except \n |
\b | Match a word boundary |
English Version
common 普通字符
escaped character 转义字符
character sets 字符集合
custom sets 次数集合
quantifier
special puncts 特殊字符(点)
backward 向后引用
assertion 预搜索
greedy reluctant 贪婪 懒惰
prompts 提示
日志
2013年12月17日 20:20 | Comments(0) | Category:linux | Tags:
清理linxu垃圾文件
2013年12月08日 18:52 | Comments(4) | Category:linux | Tags:
今天用df命令查看了自己的磁盘空间发现/分区已经使用了91%,特意上网找了一些方法以下是总结
1.使用命令 du --max-depth=1 -h 来查看各个目录的大小
参数说明 --max-depth=x ,x可以是0~n的数字,表示查看子目录的深度
-h 表示适合阅读
linux系统剪切板与vim剪切板
2013年12月08日 12:56 | Comments(3) | Category:linux | Tags:
这都是一些零散的知识
1.在vim中的复制粘贴就是在寄存器中寄放和提取字符串。你可以用:reg来查看所有的寄存器
在vim复制一个字符串 "Ny :N表示寄存器名称
在vim粘贴一个字符串 "Np
2.其中"+是也是x-windows中的寄存器,通过"+p可以在vim中调用系统中通过ctrl+c得到的内容
注意:在vim中,"+y 是复制一整行
3.yw可以复制一个字符串,不过需要光标在字符串的首字符
4.dw删除一个单词
i don konw
2013年12月02日 16:02 | Comments(3) | Category:linux | Tags:
#include <stdio.h> int main() { printf("goagent"); }
basice
for (int i=1;i<10;i++)