日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python 标准库之 commands

發(fā)布時(shí)間:2023/11/28 生活经验 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 标准库之 commands 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1. 背景

關(guān)于 commands 的說明:

  1. python 3.0 之后移除此命令,使用 subprocess代替;
  2. 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。