python中执行shell command

python3 适用,执行shell命令

使用subprocess

import subprocess

def run(args):
    out = subprocess.Popen(args, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
    stdout, stderr = out.communicate()
    return stdout

print(run(['ls', '-l']))

使用os.system

import os
os.system('ps -ef')

使用os.popen

import os
os.popen('ls')