python笔记:使用Python执行命令 python3 ``` import subprocess def cmd(cmdstr): return subprocess.check_output(cmdstr, shell=True) ``` python2 ``` import commands commands.getoutput('ls /bin/ls') ``` 如果需要实时看进度(比如ping): ``` 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() ``` 来自 大脸猪 写于 2016-11-16 15:44 -- 更新于2020-10-19 13:06 -- 1 条评论