1、从字符串里提取数字:
>>> import re
>>> string = "mysqld3"
>>> print re.findall(r"\d",string)
['3']
2、执行shell命令:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
>>>(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
>>>print status, output
3、连接其他主机:
安装模块:yum install pexpect -y
import pexpect
import pxssh
host = '192.168.137.31'
user = 'root'
password = '123qwe..'
s = pxssh.pxssh()
s.login(host,user,password,original_prompt='[$#>]')
s.sendline('date')
s.prompt()
print s.before
s.logout()
4、使用shell命令并标准输出/错误输出
import subprocess
cmd='''dir''' #定义shell命令
child = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #调用模块并输出标准输出和错误输出
stdout,stderr=child.communicate() #等待命令执行结束并将标准输出和错误输出赋值
print child.returncode,stdout,stderr #打印执行shell命令的返回代码和输出
其中若stdout,stderr=child.communicate()则print分别返回两个值;
若定义res=child.communicate()则print res,res为包含标准输出和错误输出的一个元祖
5、格式化字符串
In [1]: '{},{}'.format('fxy','girl')
Out[1]: 'fxy,girl' #默认按照顺序映射
In [2]: '{1},{0}'.format('fxy','girl')
Out[2]: 'girl,fxy' #可以指定位置映射
In [3]: '{name},{sex}'.format(sex='girl',name='fxy')
Out[3]: 'fxy,girl' #可以指定具体名称映射
In [4]: p=['fxy','girl']
In [5]: '{0[0]},{0[1]}'.format(p)
Out[5]: 'fxy,girl' #可以指定列表脚标映射
In [46]: 'a{:=>4}'.format('189')
Out[46]: 'a=189' #填充字符=,若不指定则默认填充空格
6、传递信息
服务器端:
import socket
sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 定义socket类型,网络通信,TCP
sk.bind(("127.0.0.1",80)) # 套接字绑定的IP与端口
sk.listen(5) # 开始TCP监听,数字代表在拒绝连接之前,操作系统可以挂起的最大连接数量。该值至少为1,大部分应用程序设为5就可以了
conn,address=sk.accept() # 接受TCP连接,并返回新的套接字与IP地址
print "Connect By",address
conn.sendall("hello,world") # 发送信息给客户端
客户端:
import socket
sk=socket.socket(socket.AF_INET,socket.SOCK_STREAM ) # 定义socket类型,网络通信,TCP
sk.connect(("127.0.0.1",80)) #要连接的IP和端口
data=sk.recv(1024) # 把接收的数据定义为变量
print data #输出接收到的信息
先执行服务器端,再执行客户端