国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

在Python中執行系統命令的方法示例詳解

2020-01-04 16:45:17
字體:
來源:轉載
供稿:網友

前言

Python經常被稱作“膠水語言”,因為它能夠輕易地操作其他程序,輕易地包裝使用其他語言編寫的庫。在Python/wxPython環境下,執行外部命令或者說在Python程序中啟動另一個程序的方法。

本文將詳細介紹關于Python中如何執行系統命令的相關資料,下面話不多說了,來一起看看詳細的介紹吧。

(1) os.system()

這個方法直接調用標準C的system()函數,僅僅在一個子終端運行系統命令,而不能獲取執行返回的信息。

>>> import os >>> output = os.system('cat /proc/cpuinfo') processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> output # doesn't capture output 0 

(2) os.popen()

這個方法執行命令并返回執行后的信息對象,是通過一個管道文件將結果返回。

>>> output = os.popen('cat /proc/cpuinfo') >>> output <open file 'cat /proc/cpuinfo', mode 'r' at 0x7ff52d831540> >>> print output.read() processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>><span style="font-size:14px;"> 

(3) commands模塊

>>> import commands >>> (status, output) = commands.getstatusoutput('cat /proc/cpuinfo') >>> print output processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> print status 0

注意1:在類unix的系統下使用此方法返回的返回值(status)與腳本或命令執行之后的返回值不等,這是因為調用了os.wait()的緣故,具體原因就得去了解下系統wait()的實現了。需要正確的返回值(status),只需要對返回值進行右移8位操作就可以了。

注意2:當執行命令的參數或者返回中包含了中文文字,那么建議使用subprocess。

(4) subprocess模塊

該模塊是一個功能強大的子進程管理模塊,是替換os.system, os.spawn*等方法的一個模塊。

>>> import subprocess >>> subprocess.Popen(["ls", "-l"]) <strong> # python2.x</strong> doesn't capture output >>> subprocess.run(["ls", "-l"])  <strong># python3.x</strong> doesn't capture output <subprocess.Popen object at 0x7ff52d7ee490> >>> total 68 drwxrwxr-x 3 xl xl 4096 Feb 8 05:00 com drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Desktop drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Documents drwxr-xr-x 2 xl xl 4096 Jan 21 07:44 Downloads ... ... >>>

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浦北县| 金昌市| 陵川县| 资阳市| 凌云县| 伊春市| 如东县| 长垣县| 杭锦旗| 孟津县| 类乌齐县| 汉寿县| 巧家县| 乌兰浩特市| 临猗县| 杭锦后旗| 永修县| 黎城县| 吉木萨尔县| 达日县| 都昌县| 怀宁县| 宿迁市| 特克斯县| 施秉县| 青浦区| 巴塘县| 鄂托克前旗| 越西县| 昭觉县| 广州市| 长岭县| 沙雅县| 宝应县| 嵊州市| 荣成市| 达孜县| 揭西县| 马公市| 黄平县| 达孜县|