subprocess用法笔记

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

### Windows系统查看笔记本电池使用次数 在Windows系统中,可以通过命令行工具获取笔记本电池的使用次数。具体操作如下: 1. 使用快捷键 `Win + R` 弹出运行框后输入 `cmd`,然后输入 `powercfg /batteryreport`,即可生成笔记本的电池分析报告[^1]。 2. 生成报告后,可以通过资源管理器输入报告的地址来查看报告内容,其中包含电池的设计容量、完全充电容量、循环计数等信息[^3]。 ### macOS系统查看笔记本电池使用次数 对于MacBook用户,可以通过Python编程语言执行 `ioreg` 命令并使用正则表达式从输出中提取所需的信息,包括电池的容量、最大容量和循环使用次数,并计算出电池的健康百分比。具体的Python代码如下: ```python import subprocess import re def get_battery_info(): # 执行ioreg命令获取电池信息 cmd = ['ioreg', '-r', '-w', '0', '-l', '|', 'grep', '"Battery"'] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() # 使用正则表达式提取电池信息 capacity = re.search(b'"Max Capacity" = ([0-9]+)', stdout) current_capacity = re.search(b'"Current Capacity" = ([0-9]+)', stdout) cycle_count = re.search(b'"Cycle Count" = ([0-9]+)', stdout) if capacity and current_capacity and cycle_count: capacity = int(capacity.group(1)) current_capacity = int(current_capacity.group(1)) cycle_count = int(cycle_count.group(1)) health_percentage = (current_capacity / capacity) * 100 print(f"电池容量: {capacity} mAh") print(f"当前容量: {current_capacity} mAh") print(f"循环次数: {cycle_count}") print(f"电池健康百分比: {health_percentage:.2f}%") else: print("无法获取电池信息") get_battery_info() ``` 通过上述方法,无论是Windows还是macOS系统的用户都可以方便地查询到笔记本电池的使用次数及相关健康状态信息[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值