python笔记:使用Python执行命令

2019-11-22 09:42:01 浏览数 (1)

python3

代码语言:javascript复制
import subprocess
def cmd(cmdstr):
    return subprocess.check_output(cmdstr, shell=True)

python2

代码语言:javascript复制
import commands
commands.getoutput('ls /bin/ls')

如果需要实时看进度(比如ping):

代码语言:javascript复制
import subprocess

def cmd(cmdstr):
    ps = subprocess.Popen(cmdstr, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
    while True:
        data = ps.stdout.readline()
        if data == b'':
            if ps.poll() is not None:
                break
        else:
            # print("libos output: {}".format(data.decode()))
            yield data.decode()

0 人点赞