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'))

 

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值