subprocess用法笔记

本文详细介绍了如何使用Python执行Shell命令,并提供了多个示例。包括连续执行多条Shell命令的方法,以及如何持续获取命令执行的返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

参考
https://blog.youkuaiyun.com/telenewbie/article/details/60580727

方法二:

p1 = subprocess.Popen("adb shell cd usr&&ls --color=never", stdout=subprocess.PIPE, shell=True)
print(p1.stdout.read())

同时执行多行命令:
无论是 Linux/Mac 还是 Windows 的 shell 命令都支持一条命令来执行多条命令的。一共有 &&,&,||,| 这么几种方式,这几种方式分别代表着不同的含义:

&&:command1 && command2,如果 command1 执行成功了,就执行命令 command2,如果 command1 失败了,就不会执行 command2 了。
&:command1 & command2,无论 command1 执行成功与否都会执行 command2。
||:command1 || command2,如果 command1 执行成功了,就不会执行 command2 了,如果 command1 失败了,就会继续执行 command2。
|:command1 | command2,command1 的结果做为 command2 的参数,如果 command1 失败了,整个命令也就都失败了。

Linux/Mac 下还可以使用 ; 来链接两条命令,顺序执行命令,不管成功与否都往后执行,和 & 含义一样。

参考
http://blog.sina.com.cn/s/blog_44d19b500102w585.html


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)

参考
http://blog.sina.com.cn/s/blog_44d19b500102x21i.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值