python模組整理

2021-08-07 13:08:50 字數 2754 閱讀 6469

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]: ','.format('fxy','girl')

out[2]: 'girl,fxy'   #可以指定位置對映

in [3]: ','.format(***='girl',name='fxy')

out[3]: 'fxy,girl'   #可以指定具體名稱對映

in [4]: p=['fxy','girl']

in [5]: ','.format(p)

out[5]: 'fxy,girl'    #可以指定列表腳標對映

in [46]: 'a'.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  #輸出接收到的資訊

先執行伺服器端,再執行客戶端

Python基礎模組整理

1.shutil 可以用來對檔案進行基本操作 拷貝,剪下等 2.glob 提供了乙個函式用於從目錄萬用字元搜尋中生成檔案列表 3.datetime 日期和時間的處理 4.zlib,gzip,bz2,zipfile,以及 tarfile 資料打包和壓縮 5.io 資料流,用來將資料儲存在記憶體中 6....

Python 常用模組分類整理

python 中有很多模組,很強大,但又不可能全部記住,所以,將常用模組整理整理,不會寫太詳細,就寫寫常用使用方法 本文置頂一直更新,邊用邊收集吧。1.遞迴刪除非空目錄import shutil shutil.rmtree dir name 遞迴刪除目錄2.檢視檔案字尾 filename.endsw...

collections 模組整理

collections.deque 類 雙向佇列 是乙個執行緒安全 可以快速從兩端新增或者刪除元素的資料型別。而且如果想要有一種資料型別來存放 最近用到的幾個元素 deque 也是乙個很好的選擇。這是因為在新建乙個雙向佇列的時候,你可以指定這個佇列的大小,如果這個佇列滿員了,還可以從反向端刪除過期的...