python 打開一個新進程執行系統命令, test 執行完才能獲取返回, test1 實時獲取返回結果
import subprocess def test(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) lines = p.stdout.readlines() for line in lines: tmp = line.decode('gbk').strip() print(tmp) def test1(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) for i in iter(p.stdout.readline, ''): if len(i) < 1: break print(i.decode('gbk').strip()) if __name__ == '__main__': test("ping www.baidu.com") test1("ping www.baidu.com")