subprocess模組 re模組

2022-07-24 09:21:07 字數 2679 閱讀 5984

import subprocess #匯入subprocess模組,該模組的作用為可以通過python**向終端(cmd)傳送命令

​while true:      #進行迴圈,可以讓使用者重複的進行輸入

cmd_str = input('請輸入終端命令:').strip()  #定義變數cmd_str

obj = subprocess.popen(

cmd_str, shell=true, stdout=subprocess.pipe, stderr=subprocess.pipe

)  #得到subprocess物件,語法格式為popen(cmd命令, shell=true(預設為false改為true後,可以將python**傳送到cmd中

# ),stdout=subprocess.pipe, stderr=subprocess.pipe)

success = obj.stdout.read().decode('gbk') #定義變數success為上面物件中得到的正確的結果,然後進行判斷分別輸出對應的內容

if success:

print(success)

error = obj.stderr.read().decode('gbk')  #定義變數error為上面物件中得到的錯誤的結果,然後進行判斷分別輸出對應的內容

if error:

print(error)

re模組

1.什麼是正規表示式於re模組?

正規表示式是一門獨立的技術,任何語言都可以使用正規表示式,它是由一堆特殊的字元組成的

主要型別有:字串 元字元 以及元字元的組合使用

re模組:在python中,若要使用正規表示式,必須通過re模組來實現

2.為什麼要使用正則?

正規表示式可以幫我們過濾,並提取出想要的字元資料,比如:獲取『一堆字串』中的『某些字元』

3.應用場景及使用?

爬蟲資料分析過濾資料

使用者名稱與密碼 手機認證:檢測輸入內容的合法性

#用正常的方法來做的話

while true:

phone_number = input('請輸入手機號:').strip()

#用正常的方法來做的話,這裡的條件要加很多

if len(phone_number) == 11 and (phone_number.startswith('13')) or \

phone_number.startswith('14') or phone_number.startswith('15') \

or phone_number.startswith('19'):

print('手機號碼合法!')

break

else:

print('手機號碼不合法!')

#用正規表示式的話

import re

while true:

phone_number = input('請輸入手機號:').strip()

#re.match(正規表示式, 需要過濾的字串)

if re.match('^(13|14|15|19)[0-9]$', phone_number):

print('合法')

break

else:

print('不合法')

​# 總結

# ^:代表'開頭' $:代表'結束' |:代表'或' (13|14):可以獲取乙個值,判斷是否是13或14

# :需要獲取乙個值 限制數量 :分組限制取值範圍

字元組:

- [0-9] 可以匹配到乙個0-9的字元

- [9-0]: 報錯, 必須從小到大

- [a-z]: 從小寫的a-z

- [a-z]: 從大寫a-z

- [z-a]: 錯誤, 只能從小到大,根據ascii表來匹配大小。

- [a-z]: 總大寫的a到小寫的z。

​注意: 順序必須要按照ascii碼數值的順序編寫。

​#通過re獲取指定的字元

import re

res = re.match('[a-z0-9]', 'hcy8450') #這裡代表取值的範圍 {}代表的是取值的個數 後面的字串代表目標物件(即要從**取出符合條件的值)

print(res)

print(res.group())

#結果為

hc​import re

res = re.match('[a-z0-9]', 'hcy8450')

print(res)

print(res.group())

#結果為

none

attributeerror: 'nonetype' object has no attribute 'group'

注意:#這裡我們將後面的字串第乙個字元改為大寫後,最後的結果出現了報錯;是因為match這個函式是從乙個字串的開始位置匹配正規表示式,然而這個字串的起始位置並不符合正規表示式,所以匹配失敗,返回乙個空變數,空變數並沒有group()方法,所以呼叫不成功。

​#組合使用用法

- \w\w: 匹配字母數字下劃線與非字母數字下劃線,合在一起為匹配所有。

- \d\d: 無論是數字或者非數字都可以匹配。

- \t: table

- \n: 換行

- \b: 匹配單詞結尾,tank  jasonk

- ^:

python模組之subprocess模組

import subprocess sh 3.2 ls users egon desktop grep txt mysql.txt tt.txt 事物.txt res1 subprocess.popen ls users jieli desktop shell true,stdout subproc...

python模組之subprocess模組

subprocess意在替代其他幾個老的模組或者函式,比如 os.system os.spawn os.popen popen2.commands.subprocess最簡單的用法就是呼叫shell命令了,另外也可以呼叫程式,並且可以通過stdout,stdin和stderr進行互動。subproc...

struct 模組 subprocess 模組

struct 模組 就這麼用 import struct 首先匯入此模組 res ncjewgfjsdbvdhj 隨意的值 print len res 15 只是為了展示原res的長度res1 struct.pack i len res 打包,固定i模式,len res print len res1...