Skip to content

about

当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。

subprocess模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,获取子进程的返回值等操作。

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system、os.spawn*、os.popen*、popen2.、commands.

https://docs.python.org/3.6/library/subprocess.html#module-subprocess

ping命令是否可达

参考:https://qa.1r1g.com/sf/ask/2502502901/

python
import subprocess
p = subprocess.Popen('ping www.baidu.comdadsafsd', stdout=subprocess.PIPE)
p.wait()  # 不加p.wait()的话,p.poll()拿到的结果是None
print(p.poll())  # 1

p = subprocess.Popen('ping www.baidu.com', stdout=subprocess.PIPE)
p.wait()
print(p.poll())  # 0

0表示ping通了,1表示没有ping通。

执行powershell命令

python
import subprocess
# 有些终端命令,比如yarn,需要使用powershell来执行
subprocess.run(['powershell', "-Command", "yarn docs:build"], capture_output=True, text=True)

常见报错

UnicodeDecodeError: 'gbk' codec can't decode byte 0x86 in position 149: illegal multibyte sequence

win11 + python3.11

执行下面代码时报错:

bash
subprocess.run(
    ['powershell', "-Command", "yarn docs:build"],
    capture_output=True,
    text=True,
)
"""
UnicodeDecodeError: 'gbk' codec can't decode byte 0x86 in position 149: illegal multibyte sequence
"""

解决办法,添加encoding参数.

python
res = subprocess.run(
    ['powershell', "-Command", "yarn docs:build"],
    capture_output=True,
    text=True,
    encoding='utf-8'
)