class Test: def __init__(self, path): self.path = path def test(self): p = subprocess.check_output('type ' + self.path, shell=True) # bytes类型,输出全部 print(p.decode()) # bytes -> str def test1(self): p = subprocess.Popen('type ' + self.path, stdout=subprocess.PIPE, shell=True) a = p.stdout.read() # bytes类型,输出全部 print(a.decode()) # bytes -> str def test2(self): p = subprocess.Popen('type ' + self.path, stdout=subprocess.PIPE, shell=True) a = p.stdout.readline() # bytes类型,输出一行 print(a.decode()) # bytes -> str def test3(self): p = subprocess.Popen('type ' + self.path, stdout=subprocess.PIPE, shell=True) a = p.stdout.readlines() # list类型,输出全部 print(a) def test4(self): p = subprocess.Popen('type ' + self.path, stdout=subprocess.PIPE, shell=True) print(p.stdout) for i in p.stdout: print(i) # bytes类型,输出一行,同p.stdout.readline()
1、连续执行shell命令
方法一:
cmds = [ b"alias ls='ls --color=never'", b"cd usr", b"ls", b"exit" # 这是是非常关键的,退出 ] pipe = subprocess.Popen("adb shell", stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = pipe.communicate(b"\n".join(cmds) + b"\n") print(out)
方法二:
p1 = subprocess.Popen("adb shell cd usr&&ls --color=never", stdout=subprocess.PIPE, shell=True) print(p1.stdout.read())
Linux/Mac 下还可以使用 ; 来链接两条命令,顺序执行命令,不管成功与否都往后执行,和 & 含义一样。
2、执行命令并持续获取返回值
import subprocess order = 'adb logcat' pi = subprocess.Popen(order, shell=True, stdout=subprocess.PIPE) for i in iter(pi.stdout.readline, 'b'): print(i)
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211451.html原文链接:https://javaforall.net
