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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Python 标准库之 commands

發布時間:2023/11/28 生活经验 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 标准库之 commands 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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')

總結

以上是生活随笔為你收集整理的Python 标准库之 commands的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。