Python 标准库之 commands
1. 背景
關(guān)于 commands 的說明:
- python 3.0 之后移除此命令,使用 subprocess代替;
- python 3.x 使用 subprocess 創(chuàng)建一個(gè)新進(jìn)程;
最開始的時(shí)候用 Python 學(xué)會(huì)了 os.system() 這個(gè)方法是阻塞當(dāng)前主進(jìn)程執(zhí)行的,只有該命令執(zhí)行完畢,主進(jìn)程才會(huì)繼續(xù)執(zhí)行。
os.system('ping -c 2 www.baidu.com')
而通過 os.popen() 返回的是 file read 的對(duì)象,對(duì)其進(jìn)行讀取 read() 的操作可以看到執(zhí)行的輸出。這個(gè)方法是后臺(tái)執(zhí)行,不影響后續(xù)腳本運(yùn)行。
output = os.popen('ping -c 2 www.baidu.com')
print(output.read())
2. commands 方法
commands 模塊是 Python 的內(nèi)置模塊,它主要有三個(gè)函數(shù):
| 函數(shù) | 說明 |
|---|---|
| getoutput(cmd) | Return output (stdout or stderr) of executing cmd in a shell. |
| getstatus(file) | Return output of “l(fā)s -ld file” in a string. |
| getstatusoutput(cmd) | Return (status, output) of executing cmd in a shell. |
(1). commands.getoutput(cmd) 返回Shell命令的輸出內(nèi)容:
In [30]: import commands
In [31]: commands.getoutput("pwd")
Out[31]: '/home/ubuntu'
(2). commands.getstatus(file) 返回 ls -ld file 執(zhí)行的結(jié)果:該函數(shù)已被 Python 丟棄,不建議使用,它返回 ls -ld file 的結(jié)果(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) 返回一個(gè)元組(status,output),status 代表的 shell 命令的返回狀態(tài),如果成功的話是 0;output 是 shell 的返回的結(jié)果:
In [33]: commands.getstatusoutput("pwd")
Out[33]: (0, '/home/ubuntu')
總結(jié)
以上是生活随笔為你收集整理的Python 标准库之 commands的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 标准库之 Queue
- 下一篇: Python 标准库之 subproce