Python執(zhí)行shell命令相關(guān)

導(dǎo)語(yǔ)

在編寫(xiě)python腳本的時(shí)候,偶爾想調(diào)用shell命令來(lái)執(zhí)行一些操作會(huì)比較方便些。python中目前有多種方法可以達(dá)到這樣的目的,有的僅僅是執(zhí)行命令不返回需要的結(jié)果,有些可以返回執(zhí)行的結(jié)果保存到變量,以便于后續(xù)操作

涉及到的模塊有 os.systemcommands、subprocess


下面以具體的例子說(shuō)明情況

#!/usr/bin/env bash 

import os
import commands
import subprocess

# -- os.system() --
# execute shell command in sub-terminal and can not get the return result
result1 = os.system('ls -l .')
print('result: ')
print(result1)
print('----------------------------------------')

# -- os.popen() --
# execute and can get the return result
result2 = os.popen('ls -l')
# file type
print('type: ', type(result2))

result3 = os.popen('ls -l').readlines()
# list file
print('type: ', type(result3))
print('result: ')
print(result3)
print('----------------------------------------')

# -- commands --
# import commands
# method:
#   getoutput
#   getstatusoutput
result4 = commands.getoutput('ls -l')
print('result: ')
print(result4)
print('=======')
result5_status, result5_output = commands.getstatusoutput('ls -l')
print('status: ', result5_status)
print('output: ')
print(result5_output)
print('----------------------------------------')



# subprocess
# import subprocess
# method:
#   call(["cmd","arg1", "arg2"], shell=True) refer to os.system()
#   Popen("cmd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) refer to os.popen
#
#result6 = subprocess.call("ls -l", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p = subprocess.Popen('ls *.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(p.stdout.readlines())

for line in p.stdout.readlines():
    print line,

## wait for child process to terminate, and turn returncode
retval = p.wait()
##  if ok, return 0
print(retval)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 其實(shí)應(yīng)該搞清楚何時(shí)要用python寫(xiě)腳本,何時(shí)用shell例如對(duì)于系統(tǒng)操作的業(yè)務(wù),我傾向于用shell awk ...
    帥子鍋閱讀 13,163評(píng)論 0 6
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個(gè) Awesome - XXX 系列...
    aimaile閱讀 26,840評(píng)論 6 427
  • From: https://blog.linuxeye.com/375.html 從Python 2.4開(kāi)始,Py...
    pzka158閱讀 3,116評(píng)論 0 2
  • 荷花大家都會(huì)不陌生,說(shuō)起描寫(xiě)荷花的詩(shī)句,想必大家都會(huì)想到愛(ài)蓮說(shuō)中的“予獨(dú)愛(ài)蓮之出淤泥而不染,濯清漣而不妖”一句詩(shī)。...
    新眸閱讀 663評(píng)論 0 2
  • 塊元素:主要特征是會(huì)產(chǎn)生換行效果,自動(dòng)與其他元素分離成兩行;通??梢宰鳛槿萜髟趦?nèi)部添加其他元素。 內(nèi)聯(lián)元素:不會(huì)產(chǎn)...
    frankisbaby閱讀 632評(píng)論 0 0

友情鏈接更多精彩內(nèi)容