python学习笔记

来源:互联网 发布:网络监听工具称为 编辑:程序博客网 时间:2024/06/06 00:07

1

>>> import sys
>>> logfile=open('home/huangcd/mylog.txt','a')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'home/huangcd/mylog.txt'
>>> logfile=open('/home/huangcd/mylog.txt','a')
>>> print >> logfile,'hello haungchengdu'
>>> logfile.close()
>>>

 

2

^+d 结束输入  python不支持自增自减运算符

 

3

三引号字符串可以用来包含特殊字符的字符串,所见即所得。      +用于连接字符串   *用于字符串重复。

 

4

print会在每个输出的结尾加入输入符,可以在他后面加一个,来抵消这个换行符。

 

5

>>> foo='abc'
>>> for i,ch in enumerate(foo):
...     print ch,'(%d)' %i
...
a (0)
b (1)
c (2)

 

6

>>> import subprocess
>>> subprocess.call(["ls","-l","/tmp/"])
相当于在linux上执行  ls -l  /tmp

 

7

>>> import subprocess
>>> subprocess.call("df -h",shell=True)
文件系统              容量  已用 可用 已用% 挂载点
/dev/sda2             5.7G  4.9G  582M  90% /
/dev/sda3             3.8G  256M  3.4G   7% /home
/dev/sda1             965M   29M  887M   4% /boot
tmpfs                 357M     0  357M   0% /dev/shm
0

 

8

python中,一个文件对应一个模块

 

9

In [11]: class DoubleRep(object):
   ....:     def __str__(self):
   ....:         return "hi,I'm a __str__"
   ....:     def __repr__(self):
   ....:         return "hi,i'm a __repr__"
   ....:    
   ....:    

In [12]: dr=DoubleRep()

In [13]: print dr
hi,I'm a __str__

In [14]: dr
Out[14]: hi,i'm a __repr__

10ipython的安装

下载压缩文件 加压,执行python setup.py install来安装,然后执行ipython来启动。

 

11__str__ 和__repr__用法与区别

内建函数str()和repr() (representation,表达,表示)或反引号操作符(``)可以方便地以字符串的方式获取对象的内容、类型、数值属性等信息。str()函数得到的字符串可读性好(故被print调用),而repr()函数得到的字符串通常可以用来重新获得该对象,通常情况下 obj==eval(repr(obj)) 这个等式是成立的。这两个函数接受一个对象作为其参数,返回适当的字符串。

事实上repr()和``做一样的事情,返回一个对象的“官方”字符串表示。其结果绝大多数情况下(不是所有)可以通过求值运算(内建函数eval())重新得到该对象。

str()则不同,它生成一个对象的可读性好的字符串表示,结果通常无法用eval()求值,但适合print输出。

如下例:

>>> class D(object):...     def __str__(self):...         return "a __str__"...     def __repr__(self):...         return "a __repr__"...>>> dr = D()>>> print dra __str__>>> dra __repr__>>> "%s" % dr'a __str__'>>> "%r" % dr'a __repr__'

 

12

 在ipython中用lsmagic来显示所有的魔法函数。ipython把所有以%开头的函数都当初魔法函数。

 

13

ipython结合了unix shell和python的一些功能。比如说alias可以定义变量别名。

In [5]: alias nss netstat -lptn

In [6]: nss
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name  
tcp        0      0 127.0.0.1:2208              0.0.0.0:*                   LISTEN      -                  
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      -                  
tcp        0      0 0.0.0.0:692                 0.0.0.0:*     

 

In [10]: alias achoo echo first:"|%s|",second:"|%s|"

In [11]: achoo -foo bao
first:|-foo|,second:|bao|

 

14

In [12]: store achoo
Alias stored: achoo (2, 'echo first:"|%s|",second:"|%s|"')

In [13]:

In [14]: achoo one two
first:|one|,second:|two|

 

15另一个执行linux的shell命令的方法是在命令前面加一个!通过美元符号$前缀,可以将变量传递到shell命令中

In [15]: user='huangcd'

In [16]: process='bash'

In [17]: !ps aux |rep $user|grep $process
sh: rep: command not found

In [18]: !ps aux |grep $user|grep $process
huangcd   4850  0.0  0.1   5756  1440 pts/1    Ss   20:10   0:00 bash
huangcd   5002  0.0  0.2   6020  1548 pts/2    Ss+  20:17   0:00 bash
huangcd   5433  0.0  0.0   5136   684 pts/1    S+   20:43   0:00 grep bash

In [19]: l=!ps aux |grep $user|grep $process(把所得到的值传递给l)
 ==
['huangcd   4850  0.0  0.1   5756  1440 pts/1    Ss   20:10   0:00 bash',
 'huangcd   5002  0.0  0.2   6020  1548 pts/2    Ss+  20:17   0:00 bash',
 'huangcd   5499  0.0  0.0   5136   716 pts/1    S+   20:45   0:00 grep bash']

 

16__IP是实现从别名到shell命令映射的地方。可以通过__IP.alias_table来查看所有的别名映射。通过rehash来实现变量刷新。

In [15]: user='huangcd'

In [16]: process='bash'

In [17]: !ps aux |rep $user|grep $process
sh: rep: command not found

In [18]: !ps aux |grep $user|grep $process
huangcd   4850  0.0  0.1   5756  1440 pts/1    Ss   20:10   0:00 bash
huangcd   5002  0.0  0.2   6020  1548 pts/2    Ss+  20:17   0:00 bash
huangcd   5433  0.0  0.0   5136   684 pts/1    S+   20:43   0:00 grep b

In [22]: __IP.alias_table
Out[22]:
{'achoo': (2, 'echo first:"|%s|",second:"|%s|"'),
 'cat': (0, 'cat'),
 'clear': (0, 'clear'),
 'cp': (0, 'cp -i'),
 'lc': (0, 'ls -F -o --color'),
 'ldir': (0, 'ls -F -o --color %l | grep /$'),
 'less': (0, 'less'),
 'lf': (0, 'ls -F -o --color %l | grep ^-'),
 'lk': (0, 'ls -F -o --color %l | grep ^l'),
 'll': (0, 'ls -lF'),
 'ls': (0, 'ls -F'),
 'lx': (0, 'ls -F -o --color %l | grep ^-..x'),

In [23]: len(__IP.alias_table)
Out[23]: 17

In [24]: rehash

In [25]: len(__IP.alias_table)
Out[25]: 2296

 

17

In [34]: cd /tmp
/tmp

In [35]: pwd
Out[35]: '/tmp'

In [36]: cd -
/home/huangcd

18

In [42]: cd /tmp
/tmp

In [43]: bookmark t

In [44]: bookmark muzak /home/huangcd

In [45]: bookmark -l
Current bookmarks:
muzak -> /home/huangcd
t     -> /tmp

In [46]: bookmark -d t

In [47]: bookmark -l
Current bookmarks:
muzak -> /home/huangcd

 

19列出历史访问目录

 In [48]: dhist
Directory history (kept in _dh)
0: /home/huangcd
1: /tmp
2: /home/huangcd
3: /tmp
4: /home/huangcd
5: /tmp
In [50]: dhist 2 4
Directory history (kept in _dh)
2: /home/huangcd
3: /tmp

 

20shell和python的结合

In [51]: for i in range(10):
   ....:     !date>${i}.txt
   ....:    
   ....:    

In [52]: ls
0.txt             orbit-huangcd/
1.txt             rstdir1382761865-jG0Ewl
2.txt             scim-bridge-0.3.0.lockfile-500@localhost:0.0
3.txt             scim-bridge-0.3.0.socket-500@localhost:0.0=
4.txt             scim-helper-manager-socket-huangcd=
5.txt             scim-panel-socket:0-huangcd=
6.txt             scim-socket-frontend-huangcd=
7.txt             ssh-xlRrye4562/
8.txt             swap
9.txt             virtual-huangcd.5JNBYo/

In [53]: cat 0.txt
2013年 10月 28日 星期一 21:55:02 CST

 

21

 


In [51]: for i in range(10):
   ....:     !date>${i}.txt
   ....:    
   ....:    

In [52]: ls
0.txt             orbit-huangcd/
1.txt             rstdir1382761865-jG0Ewl
2.txt             scim-bridge-0.3.0.lockfile-500@localhost:0.0
3.txt             scim-bridge-0.3.0.socket-500@localhost:0.0=
4.txt             scim-helper-manager-socket-huangcd=
5.txt             scim-panel-socket:0-huangcd=
6.txt             scim-socket-frontend-huangcd=
7.txt             ssh-xlRrye4562/
8.txt             swap
9.txt             virtual-huangcd.5JNBYo/

 

 

22
>>> res=subprocess.Popen(['uname','-sv'],stdout=subprocess.PIPE)
>>> uname=res.stdout.read().strip()
>>> uname
'Linux #1 SMP Tue Oct 22 12:57:43 EDT 2013'
>>> 'linux' in uname
False
>>> uname.index('linux')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: substring not found
>>> uname.find('linux')
-1
>>> smp_index=uname.index('SMP')
>>> smp_index
9
>>> uname[smp_index:]
'SMP Tue Oct 22 12:57:43 EDT 2013'

 

23字符串操作

 >>> some_string ="Raymond luxury-yacht"
>>> some_string.startswith("Raymond")
True
>>> some_string.endswith("luxury-yacht")
True
>>> some_string.startswith("Raymond")
True
>>> some_string.endswith("luxury-yacht")
True
>>> some_string[:len("Raymond")]=="Raymond"
True

 

23lstrip()删除前导空白,rstrip()删除结尾空白,strip()删除前后空白。

>>> spaceious_string ="\n\t some Non-spacious text\n\t\r"
>>> spaceious_string
'\n\t some Non-spacious text\n\t\r'
>>> pring spaceious_string
  File "<stdin>", line 1
    pring spaceious_string
                         ^
SyntaxError: invalid syntax
>>> print spaceious_string

         some Non-spacious text

>>> spacious_string.lstrip()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spacious_string' is not defined
>>> spaceious_string.lstrip()
'some Non-spacious text\n\t\r'

In [1]: xml_tag="<some_tag>"

In [2]: xml_tag.lstrip("<")
Out[2]: 'some_tag>'

In [3]: xml_tag.rstrip(">")
Out[3]: '<some_tag'
In [5]: xml_tag.strip("<").strip(">")
Out[5]: 'some_tag'

In [6]: lt_ls_str="<><><>gt lt str<in<>sd>"

In [7]: lt_ls_str.strip("<>")
Out[7]: 'gt lt str<in<>sd'

 

24字符串操作函数

In [8]: mixed_case_string = "VOrpal BUnny"

In [9]: mixed_case_string=="vorpal bunny"
Out[9]: False

In [10]: mixed_case_string.upper()
Out[10]: 'VORPAL BUNNY'

In [11]: mixed_case_string.lower()
Out[11]: 'vorpal bunny'

 

 

25split()用法,默认是用空格分切。

In [1]: muti_delin_string = "pos1xxxpos2xxxpos3"

In [2]: muti_delin_string.split("xxx")
Out[2]: ['pos1', 'pos2', 'pos3']

In [3]: muti_delin_string.sp
muti_delin_string.split       muti_delin_string.splitlines

In [3]: muti_delin_string.split("xx")
Out[3]: ['pos1', 'xpos2', 'xpos3']

In [4]: two_field_string ="3243,this is a  freefrom,plain text,string"

In [5]: two_field_string.split(',',1)
Out[5]: ['3243', 'this is a  freefrom,plain text,string']

In [6]: two_field_string.split(',',2)
Out[6]: ['3243', 'this is a  freefrom', 'plain text,string']
In [7]: two_field_string.split()
Out[7]: ['3243,this', 'is', 'a', 'freefrom,plain', 'text,string']

In [8]: multiline_string ='''this
   ...: is
   ...: a
   ...: piece of
   ...: text'''

In [9]: mu
multiline_string   muti_delin_string 

In [9]: multiline_string.split()
Out[9]: ['this', 'is', 'a', 'piece', 'of', 'text']

In [10]: lines=multiline_string.spl
multiline_string.split       multiline_string.splitlines

In [10]: lines=multiline_string.splitlines()

In [11]: lines
Out[11]: ['this', 'is', 'a ', 'piece of', 'text']



 

 

26join()操作对象是一序列字符串,不能是其他的类型。

In [1]: some_list=range(10)

In [2]: some_list
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [3]: ",".join(some_list)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/huangcd/<ipython console>

TypeError: sequence item 0: expected string, int found

In [4]: ",".join([str(i) for i in some_list])
Out[4]: '0,1,2,3,4,5,6,7,8,9'

 

27 replace()方法

In [5]: replacable_string = "trancendental hibernational nation"

In [6]: replacable_string.replace("nation","natty")
Out[6]: 'trancendental hibernattyal natty'

 

28unicode字符串的创建于处理

In [7]: unicode_string =u"this id a unicode string"

In [8]: unicode_string
Out[8]: u'this id a unicode string'
In [9]: print unicode_string
this id a unicode string
In [10]: unicode('this is a unicode string')
Out[10]: u'this is a unicode string'

In [11]: unicode_string=u'abc_\u03a0\u03a3\u03a9_\u0414\u0424\u042F'

In [12]: uni
unichr          unicode         unicode_string 

In [12]: unicode_string
Out[12]: u'abc_\u03a0\u03a3\u03a9_\u0414\u0424\u042f'

In [13]: print unicode_string
abc_ΠΣΩ_ДФЯ

In [14]: print unicode_string.encode('utf-8')
abc_ΠΣΩ_ДФЯ

In [15]: unicode_string.split()
Out[15]: [u'abc_\u03a0\u03a3\u03a9_\u0414\u0424\u042f']

 

29python的正则表达式源自于库,而不是语言自身的语法特征,因此在使用之前必须载入re模块。

In [16]: import re

In [17]: re_string="{{(.*?)}}"

In [18]: some_string ="this id a string with {{words}} enbedded in\"
------------------------------------------------------------
   File "<ipython console>", line 1
     some_string ="this id a string with {{words}} enbedded in\"
                                                               ^
SyntaxError: EOL while scanning single-quoted string


In [19]: some_string ="this id a string with {{words}} enbedded in\
   ....: {{curly bnradf}} to show {{}} of {{regular expp}}"

In [20]: for match in re.find
re.findall   re.finditer 

In [20]: for match in re.findall(re_string,some_string):
   ....:     print "MATCH->",match
   ....:    
   ....:    
MATCH-> words
MATCH-> curly bnradf
MATCH->
MATCH-> regular expp

 

30python中有两种正则表达式的使用方式,一种是re模块中的函数,还有就是创建一个已经编译的正则表达式对象,通过re.compile()来创建,它包含一些正则表达式方法。

也通过re.compile()来编译。下面是已编译模式:

In [21]: import re

In [22]: re_obj=re.compile("{{.*?}}")

In [23]:  some_string ="this id a string with {{words}} enbedded in\
   ....:    ....: {{curly bnradf}} to show {{}} of {{regular expp}}"

In [25]: for match in re_obj.findall(some_string):
   ....:     print "MATCH->",match
   ....:    
   ....:    
MATCH-> {{words}}
MATCH-> {{curly bnradf}}
MATCH-> {{}}
MATCH-> {{regular expp}}
编译后的正则表达式运行比非编译的正则表达式块一半左右。

 

 

31最常用的几个正则表达式方法是 findall(),finditer(0,match(),search(),split()等等。正则表达式与原始字符串的区别是正则表达式前面有一个r。

In [41]: import re

In [42]: rwa_pattern=r'\b[a-z]+\b'

In [43]: non_rwa_pattern='\b[a-z]\b'

In [44]: some_string = 'a few little words'

In [46]: re.findall(rwa_pattern,some_string)
Out[46]: ['a', 'few', 'little', 'words']
In [47]: re.findall(non_rwa_pattern,some_string)
Out[47]: []

 

In [48]: import re

In [49]: re_obj=re.compile(r'\bt.*?e\b')

In [50]: re_obj.findall("time tame tune tint tire")
Out[50]: ['time', 'tame', 'tune', 'tint tire']

In [51]: re_obj=re.compile(r'\bt\w*e\b')

In [53]: re_obj.findall("time tame tune tint tire")
Out[53]: ['time', 'tame', 'tune', 'tire']

 

 

32finditer()返回一个找到的匹配对象,以迭代的方式返回。

33math()和search()功能相似,match()从指定位置开始匹配,search()从指定位置开始搜索,在指定的位置结束搜索。

In [54]: import re

In [55]: re_obj=re.compile('foo')

In [56]: search_string=' foo'

In [57]: re_obj.search(search_string)
Out[57]: <_sre.SRE_Match object at 0xb7999410>

In [58]: re_obj.match(search_string)

 

search()和match()z主要是我的模式第一次匹配的内容是什么?

 

 

34 python主要通过file内建类来处理文不能数据。

我们处理文件的第一步是建立一个文件对象,通过文件对象来处理文件。可以通open()函数来实现,

 infile=open("mylog.txt","r")

In [62]: print infile.read()
hello haungchengdu


In [63]: print infile.read()


In [64]: infile.clo
infile.close   infile.closed 

In [64]: infile.close()

In [65]: outputfile=open("mylog.txt","w")

In [66]: outputfile.wri
outputfile.write       outputfile.writelines 

In [66]: outputfile.write("this is \n randow \n output test\n")

In [67]: outputfile.close()
try:
   ....:     f=open('mylog.txt','a')
   ....:     f.write('quick line here\n')
   ....: finally:
   ....:     f.close()

 

35 with语句使用上下文管理器这个简单对象,具有__enter__()和__exit()__方法,当一个对象在表达式中被创建以后,__enter__()

方法被调用,当with块结束以后,即使发生异常,上下文管理器的__exit__()方法也会被调用。

 

36三个file方法来读取文本文件中的数据,read(),readline(),readlines(),read()返回独到的字符数个数,如果没有参数规定默认尽量独到末尾。

readline()表示一次性读取一行,如果有个数参数就一直读知道末尾或者读取足够数据。

 

 37python通过os模块的函数来调用其他语言编写的模块,脚本等,也可以用来执行系统命令。

In [20]: import os

In [21]: result = os.system('cat /etc/motd')

In [22]: result
Out[22]: 0

In [23]: result = os.system('uname -a')
Linux localhost.localdomain 2.6.18-371.1.2.el5 #1 SMP Tue Oct 22 12:57:43 EDT 2013 i686 i686 i386 GNU/Linux

In [24]: result
Out[24]: 0
In [25]: result = os.system('dir')
c           ipython-0.8.2  mytest.py   regular_express.txt
Desktop     mylog.txt      mytest.py~  vmware-tools-distrib
gendata.py  mylog.txt~     python      新文件~

In [26]: import os

In [27]: f = os.popen('uname -a')

In [28]: data = f.readline()

In [29]: f.close()

In [30]: print data,
Linux localhost.localdomain 2.6.18-371.1.2.el5 #1 SMP Tue Oct 22 12:57:43 EDT 2013 i686 i686 i386 GNU/Linux

 

 >>> f=Popen(('uname','a'),stdout=PIPE).stdout
>>> uname: 额外的操作数 “a”
请尝试执行“uname --help”来获取更多信息。
f=Popen(('uname','-a'),stdout=PIPE).stdout
>>> data = f.readline()
>>> f.close()
>>> print data,
Linux localhost.localdomain 2.6.18-371.1.2.el5 #1 SMP Tue Oct 22 12:57:43 EDT 2013 i686 i686 i386 GNU/Linux
>>> f = Popen('who',stdout=PIPE).stdout
>>> data = [eachLine.strip() for eachLine in f]
>>> f.close()
>>> for eachLine in data:
...     print eachLine
...
huangcd  :0           2013-10-31 08:34
huangcd  pts/1        2013-10-31 08:53 (:0.0)