python之subprocess.Popen常用案例

import subprocess

#最基本的启动进程方式类似cmd下执行: notepad.exe text.txt 命令
obj = subprocess.Popen(['notepad.exe','text.txt'], shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
print(obj.stderr.read().decode('gbk'))

#进入某个环境执行语句,需要依赖上次执行的状态
obj = subprocess.Popen('python', shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
obj.stdin.write('print(6+7)'.encode('utf-8'))
info,err = obj.communicate()
print(info.decode('gbk'))

#进入某个环境执行语句(adb shell),注意shell内部命令需要带\n,执行完后一定记得执行exit命令退出,否则会阻塞
obj = subprocess.Popen(['adb', 'shell'], shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
obj.stdin.write('ls\n'.encode('utf-8'))
obj.stdin.write('exit\n'.encode('utf-8'))  #重点,一定要执行exit
info,err = obj.communicate()
print(info.decode('gbk'))
print(err.decode('gbk'))

#进入某个环境执行语句(adb shell),命令用列表方式全部列出
cmds = [
    "cd data",
    'cd data',
    "ls",
    "exit",#执行退出,重要
]
obj = subprocess.Popen("adb shell", shell= True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
info = obj.communicate(("\n".join(cmds) + "\n").encode('utf-8'));
for item in info:
    if item:
        print(item.decode('gbk'))

#当需要连续实时输出信息时,采用obj.stdout.readline方式读取
import chardet
obj = subprocess.Popen("adb logcat", shell = True, stdin=subprocess.PIPE, stdout=subprocess.PIPE ,stderr=subprocess.PIPE)
for item in iter(obj.stdout.readline,'b'):
    encode_type = chardet.detect(item)
    if encode_type['encoding'] == 'utf-8':
        print(item.decode('utf-8'))
    elif encode_type['encoding'] == 'Windows-1252':
        print(item.decode('Windows-1252'))
    else:
        print(item.decode('gbk'))

你可能感兴趣的:(python小功能)