天天看點

一個有用函數:python調用shell指令

在安裝lxml時遇到問題,認識了這個函數,覺得挺有用,記錄如下:

def run_command(cmd, *args):

if not cmd:

return ''

if args:

cmd = ' '.join((cmd,) + args)

try:

import subprocess

except ImportError:

# Python 2.3

_, rf, ef = os.popen3(cmd)

else:

# Python 2.4+

p = subprocess.Popen(cmd, shell=True,

stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rf, ef = p.stdout, p.stderr

errors = ef.read()

if errors:

print("ERROR: %s" % errors)

return rf.read().strip() 

函數的作用是調用一個shell指令,可帶參數,可以傳回執行結果。

如:

print run_command("ls","-al")