Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
一些基础知识
交互式shell:
bash
python
在bash和python中执行命令的对比
下面的例子其实看不出区别多大,但是我们能看到不同的shell做同样一件事情,使用的命令并不相同。
Shell:
$ echo"hello" hello
Python:
>>> print"hello" hello
在python中执行命令
在bash中执行ls -l /tmp,那么在python中要调用系统命令该如何操作呢?
>>> import subprocess >>> subprocess.call(['ls','-l','/tmp']) total 16 -rw-r--r--. 1 root root 271 Oct 18 11:49 f1.py drwx------. 3 root root 16 Oct 18 10:26 systemd-private-e67cf4721d8a406485ba836c215f04aa-colord.service-elJaMh drwx------. 3 root root 16 Oct 18 10:26 systemd-private-e67cf4721d8a406485ba836c215f04aa-cups.service-Pj9mNR drwx------. 3 root root 16 Oct 18 10:26 systemd-private-e67cf4721d8a406485ba836c215f04aa-rtkit-daemon.service-wTmvkM drwx------. 3 root root 16 Oct 19 10:18 systemd-private-f1d37d63f6684cafa2e6d7f420dacffe-colord.service-iMUb3u drwx------. 3 root root 16 Oct 19 10:18 systemd-private-f1d37d63f6684cafa2e6d7f420dacffe-cups.service-sEomwX drwx------. 3 root root 16 Oct 19 10:18 systemd-private-f1d37d63f6684cafa2e6d7f420dacffe-rtkit-daemon.service-9bGrzQ -rw-r--r--. 1 root root 106 Oct 17 16:38 test.py -rw-r--r--. 1 root root 109 Oct 17 16:53 useradd.py -rw-r--r--. 1 root root 74 Oct 17 16:52 userlist 0
[root@workstation0 ~]# cat sysinfo.py #!/usr/bin/env python # encoding=utf-8 # A System Information Gathering Script import subprocess #Command 1 uname = "uname" uname_arg = "-a" print("系统信息 Gathering system information with %s command:\n" %uname) subprocess.call([uname,uname_arg]) #Command 2 diskspace = "df" diskspace_arg = "-h" print("磁盘空间 Gathering diskspace information %s command:\n" % diskspace) subprocess.call([diskspace,diskspace_arg])
[root@workstation0 ~]# python sysinfo.py 系统信息 Gathering system information with uname command:
Linux workstation0.example.com 3.10.0-327.el7.x86_64 #1 SMP Thu Oct 29 17:29:29 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux 磁盘空间 Gathering diskspace information df command:
Filesystem Size Used Avail Use% Mounted on /dev/vda2 20G 3.0G 17G 15% / devtmpfs 483M 0 483M 0% /dev tmpfs 497M 84K 497M 1% /dev/shm tmpfs 497M 6.9M 490M 2% /run tmpfs 497M 0 497M 0% /sys/fs/cgroup /dev/vda1 197M 125M 73M 64% /boot tmpfs 100M 16K 100M 1% /run/user/42 tmpfs 100M 0 100M 0% /run/user/0
对比bash的写法
[root@workstation0 ~]# cat sysinfo.bash #!/bin/bash echo"系统信息 Gathering system information with uname command:" uanme -r echo"磁盘信息 Gathering system information with df command:" df -h [root@workstation0 ~]# bash sysinfo.bash 系统信息 Gathering system information with unamecommand: sysinfo.bash: line 3: uanme: command not found 磁盘信息 Gathering system information with dfcommand: Filesystem Size Used Avail Use% Mounted on /dev/vda2 20G 3.0G 17G 15% / devtmpfs 483M 0 483M 0% /dev tmpfs 497M 84K 497M 1% /dev/shm tmpfs 497M 6.9M 490M 2% /run tmpfs 497M 0 497M 0% /sys/fs/cgroup /dev/vda1 197M 125M 73M 64% /boot tmpfs 100M 16K 100M 1% /run/user/42 tmpfs 100M 0 100M 0% /run/user/0
>>> defpyfunc(): ... print("hello function") ... >>> pyfunc() hello function >>> for i inrange(4): ... pyfunc() ... hello function hello function hello function hello function
我们再使用bash完成以上功能
[root@workstation0 ~]# shfunc() > { > echo"hello function" > } [root@workstation0 ~]# for i in `seq 1 4` > do > shfunc > done hello function hello function hello function hello function
[root@workstation0 ~]# python Python 2.7.5 (default, Oct 11 2015, 17:47:16) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sysinfo_func >>> sysinfo_func.disk_func() 磁盘空间 Gathering diskspace information df command:
Filesystem Size Used Avail Use% Mounted on /dev/vda2 20G 3.0G 17G 15% / devtmpfs 483M 0 483M 0% /dev tmpfs 497M 84K 497M 1% /dev/shm tmpfs 497M 6.9M 490M 2% /run tmpfs 497M 0 497M 0% /sys/fs/cgroup /dev/vda1 197M 125M 73M 64% /boot tmpfs 100M 16K 100M 1% /run/user/42 tmpfs 100M 0 100M 0% /run/user/0 >>> sysinfo_func.main() 系统信息 Gathering system information with uname command:
Linux workstation0.example.com 3.10.0-327.el7.x86_64 #1 SMP Thu Oct 29 17:29:29 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux 磁盘空间 Gathering diskspace information df command:
Filesystem Size Used Avail Use% Mounted on /dev/vda2 20G 3.0G 17G 15% / devtmpfs 483M 0 483M 0% /dev tmpfs 497M 84K 497M 1% /dev/shm tmpfs 497M 6.9M 490M 2% /run tmpfs 497M 0 497M 0% /sys/fs/cgroup /dev/vda1 197M 125M 73M 64% /boot tmpfs 100M 16K 100M 1% /run/user/42 tmpfs 100M 0 100M 0% /run/user/0 >>> help(sysinfo_func)
Help on module sysinfo_func:
NAME sysinfo_func
FILE /root/sysinfo_func.py
DESCRIPTION # encoding=utf-8 #A System Information Gathering Script
[root@workstation0 ~]# wget https://github.com/downloads/ipython/ipython/ipython-0.13.1.tar.gz [root@workstation0 ~]# tar -xf ipython-0.13.1.tar.gz [root@workstation0 ~]# cd ipython-0.13.1/ [root@workstation0 ipython-0.13.1]# ls docs IPython ipython.py PKG-INFO README.rst scripts setupbase.py setupegg.py setupext setup.py
[root@foundation0 ipython-0.13.1]# python setup.py install \============================================================================ BUILDING IPYTHON python: 2.7.5 (default, Oct 11 2015, 17:47:16) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] platform: linux2
OPTIONAL DEPENDENCIES sphinx: Not found (required for building documentation) pygments: 1.4 nose: Not found (required for running the test suite) pexpect: 2.3 pyzmq: no (required for qtconsole, notebook, and parallel computing capabilities) readline: yes
[root@workstation0 ipython-0.13.1]# ipython Python 2.7.5 (default, Oct 11 2015, 17:47:16) Type "copyright", "credits" or "license" for more information.
IPython 0.13.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details.
你可以用单引号指定字符串,如 ’Quote me on this’ 。所有的空白,即空格和制表符都照原样保留。
双引号
在双引号中的字符串与单引号中的字符串的使用完全相同,例如 “What’s your name?” 。
利用三引号(“””or”’)
你可以指示一个多行的字符串。你可以在三引号中自由的使用单引号和双引号。
In [9]: str1='Quote me on this'
In [10]: str2="what's your name?"
In [11]: str3='''this is a multi-line string. ....: this is the second line. ....: "what's your name?" I asked. ....: he said "Bond, James Bond." ....: '''
In [12]: print str1 Quote me on this
In [13]: print str2 what's your name? In [14]: print str3 this is a multi-line string. this is the second line. "what's your name?" I asked. he said "Bond, James Bond."
In [4]: some_str = "this is a string with {{words}} embedded in\ ...: {{curly brackets}} to show an {{example}} of {{regular expressions}}"
In [5]: for match in re.findall(re_str,some_str): ...: print"match-->",match ...: match--> words match--> curly brackets match--> example match--> regular expressions
In [6]: re_str="a{2,}"
In [7]: some_str="apple aaa abc"
In [8]: for line in re.findall(re_str,some_str): ...: print"match-->",line ...: match--> aaa
In [9]: re.findall(re_str,some_str) Out[9]: ['aaa']
原始字符串与正则表达式中使用的原始字符串
In [10]: import re
In [11]: raw_p = r'\b[a-z]+\b'
In [12]: now_raw_p = '\b[a-z]+\b'
In [13]: some_str = 'a few little words'
In [14]: re.findall(raw_p,some_str) Out[14]: ['a', 'few', 'little', 'words']
In [15]: raw_p1 = r'^a'
In [16]: re.findall(raw_p1,some_str) Out[16]: ['a']
In [23]: re.findall(now_raw_p,some_str) Out[23]: []
>>> name='shell' >>> print('my name is {0} and the length of name is {1}'.format(name,len(name))) my name is shell and the length of name is 5 >>> print('my name is %s and the length of name is %d' % (name,len(name))) my name is shell and the length of name is 5
In [29]: try: ....: f = open('writeable.txt','w') ....: f.write('quick line here\n') ....: finally: ....: f.close() ....: In [30]: open('writeable.txt','r').read() Out[30]: 'quick line here\n'
不用调用close()方法,还可以通过关键词with语句,来关闭文件:
In [31]: withopen('writeable.txt','w') as f: ....: f.write('ok\n') ....:
In [32]: open('writeable.txt','r').read() Out[32]: 'ok\n'
In [33]: f Out[33]: <closed file 'writeable.txt', mode 'w' at 0x28074b0>
In [39]: fs="this is a\n multiline string.\n" In [43]: f=StringIO(fs)
In [44]: f.readline() Out[44]: 'this is a\n'
In [45]: f.readline() Out[45]: ' multiline string.\n
urllib
从web服务器读取文件,urllib()
In [1]: import urllib
In [2]: url_file = urllib.urlopen("http://172.25.254.254/content/students/03-lab/10-mysql5.7-root-password-break")
In [3]: urllib_docs = url_file.read()
In [5]: url_file.close()
In [6]: len(urllib_docs) Out[6]: 260
In [7]: urllib_docs[:80] Out[7]: 'RHEL7 \xe5\xbf\x98\xe8\xae\xb0mysql5.7\xe7\x9a\x84\xe5\xaf\x86\xe7\xa0\x81\n\xe4\xbf\xae\xe6\x94\xb9\xe9\x85\x8d\xe7\xbd\xae\xe6\x96\x87\xe4\xbb\xb6/etc/my.cnf\n\xe6\xb7\xbb\xe5\x8a\xa0\xe4\xb8\x80\xe4\xb8\xaa\xe9\x80\x89\xe9\xa1\xb9 s'
In [8]: urllib_docs[-80:] Out[8]: 'art mysqld\n\n# mysql\n>alter user root@localhost identified by "U:pl:oo00king:" ;\n'
加载urllib模块,使用urllib创建一个类文件对象,并命名为url_file;
将url_file的内容读入urllib_docs的字符串中;
通过url_file.close()将文件关闭。
课后习题
安装ipython
数字
2*(3+4)
2*3+4
2+3*4
通过什么工具你可以找到一个数字的平方根以及它的平方?
表达式1+0.2+3的结果是什么类型?
怎样能够截断或舍去浮点数的小数部分?
怎样将一个整数转化为浮点数?
如何将一个整数显示成八进制、十六进制、二进制的形式?
如何将一个八进制、十六进制、二进制的字符串转化成平常的整数?
习题解答
In [1]: 2*(3+4) Out[1]: 14
In [2]: 2*3+4 Out[2]: 10
In [3]: 2+3*4 Out[3]: 14
In [4]: import math #平方根 In [5]: math.sqrt(4) Out[5]: 2.0 #平方 In [7]: pow(2,2) Out[7]: 4 #浮点数 In [8]: 1+0.2+3 Out[8]: 4.2 #浮点变整数 In [9]: int(4.2) Out[9]: 4
In [11]: math.trunc(4.2) Out[11]: 4 #整数变浮点 In [12]: float(4) Out[12]: 4.0 #10-八进制 In [16]: oct(10) Out[16]: '012' #10-十六进制 In [17]: hex(10) Out[17]: '0xa' #10-二进制 In [18]: bin(10) Out[18]: '0b1010'
tel_string = '+86 10010 +21 20145 +45 15264' tel_list = tel_string.split() for i in tel_list: if i.startswith('+'): print i
字符编码问题
In [108]: print u'你好'.encode('utf-8') 你好
In [109]: print str_b 你好
In [110]: print '你好'.encode('utf-8') --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-110-12163d00438d> in <module>() ----> 1 print'你好'.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
In [112]: '你好'.decode('utf-8') Out[112]: u'\u4f60\u597d'
获取帮助
[root@workstation0 ~]# python Python 2.7.5 (default, Oct 11 2015, 17:47:16) [GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help()
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> print help> re help> exit help> q
You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt.
从键盘输入
bash #!/bin/bash read -p "plz input yourname:" name echo "your name is $name"
#!/usr/bin/env python
try: name=raw_input('plz input yourname') excapt: name=input('plz input yourname') print'your name is {}'.format(name)
username is ;uid is ;groups is ;password is 初始组是 附加组是
脚本如下:
#!/usr/bin/env python # -*- coding: utf-8 -*-
a_file = open('/tmp/useraddlist','r') a_list = a_file.readlines() for i in a_list: line_list = i.split() print"username is {},uid is {},groups are {},password is {}".format(line_list[0],line_list[1],line_list[2],line_list[3]) g_str = line_list[2] g_list = g_str.split(',') print"初始组是:{}".format(g_list[0]) print"附加组是:{}".format('和'.join(g_list[1:]))
运行结果为:
username is dabao,uid is 888,groups are xuexi,it,password is uplooking 初始组是:xuexi 附加组是:it username is lucy,uid is 889,groups are sales,it,password is uplooking 初始组是:sales 附加组是:it username is lily,uid is 899,groups are pro,aa,bb,password is uplooking 初始组是:pro 附加组是:aa和bb