目錄html
subprocess模塊容許你去建立一個新的進程讓其執行另外的程序,並與它進行通訊,獲取標準的輸入、標準輸出、標準錯誤以及返回碼等。更多查看官網:https://docs.python.org/2/library/subprocess.html?highlight=subprocess#frequently-used-argumentspython
import subprocess import subprocess ''' sh-3.2# ls /Users/nick/Desktop |grep txt$ mysql.txt tt.txt 事物.txt ''' res1 = subprocess.Popen('ls /Users/jieli/Desktop', shell=True, stdout=subprocess.PIPE) res = subprocess.Popen('grep txt$', shell=True, stdin=res1.stdout, stdout=subprocess.PIPE) print(res.stdout.read().decode('utf-8')) # 等同於上面,可是上面的優點在於,一個數據流能夠和另一個數據流交互,能夠經過爬蟲獲得結果真後交給grep res1 = subprocess.Popen('ls /Users/jieli/Desktop |grep txt$', shell=True, stdout=subprocess.PIPE) print(res1.stdout.read().decode('utf-8')) # windows下: # dir | findstr 'test*' # dir | findstr 'txt$' res1 = subprocess.Popen(r'dirC:\Users\Administrator\PycharmProjects\test\函數備課', shell=True, stdout=subprocess.PIPE) res = subprocess.Popen('findstr test*', shell=True, stdin=res1.stdout, stdout=subprocess.PIPE) # subprocess使用當前系統默認編碼,獲得結果爲bytes類型,在windows下須要用gbk解碼 print(res.stdout.read().decode('gbk'))