Python 标准库之 commands
生活随笔
收集整理的這篇文章主要介紹了
Python 标准库之 commands
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 背景
關于 commands 的說明:
- python 3.0 之后移除此命令,使用 subprocess代替;
- 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')
總結
以上是生活随笔為你收集整理的Python 标准库之 commands的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 标准库之 Queue
- 下一篇: Python 标准库之 subproce