Python 标准库之 commands

博客介绍了Python中commands相关内容。Python 3.0后移除commands命令,用subprocess代替,3.x用subprocess创建新进程。还提及os.system()和os.popen()方法特点。此外,介绍了commands模块的三个函数,其中getstatus函数已被丢弃。

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

1. 背景

关于 commands 的说明:

  1. python 3.0 之后移除此命令,使用 subprocess代替;
  2. python 3.x 使用 subprocess 创建一个新进程;

最开始的时候用 Python 学会了 os.system() 这个方法是阻塞当前主进程执行的,只有该命令执行完毕,主进程才会继续执行。

os.system('ping -c 2 www.baidu.com')

而通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。这个方法是后台执行,不影响后续脚本运行。

output = os.popen('ping -c 2 www.baidu.com')
print(output.read())

2. commands 方法

commands 模块是 Python 的内置模块,它主要有三个函数:

函数说明
getoutput(cmd)Return output (stdout or stderr) of executing cmd in a shell.
getstatus(file)Return output of “ls -ld file” in a string.
getstatusoutput(cmd)Return (status, output) of executing cmd in a shell.

(1). commands.getoutput(cmd) 返回Shell命令的输出内容:

In [30]: import commands
In [31]: commands.getoutput("pwd")
Out[31]: '/home/ubuntu'

(2). commands.getstatus(file) 返回 ls -ld file 执行的结果:该函数已被 Python 丢弃,不建议使用,它返回 ls -ld file 的结果(String)

In [42]: commands.getstatus("/home/ubuntu/Downloads/")
Out[42]: 'drwxr-xr-x 2 ubuntu ubuntu 4096 5\xe6\x9c\x88   4 15:36 /home/ubuntu/Downloads/'

(3). commands.getstatusoutput(cmd) 返回一个元组(status,output),status 代表的 shell 命令的返回状态,如果成功的话是 0;output 是 shell 的返回的结果:

In [33]: commands.getstatusoutput("pwd")
Out[33]: (0, '/home/ubuntu')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wohu007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值