import subprocess # 返回命令執行結果 # result = subprocess.call('ls -l', shell=True) # result = subprocess.call(['ls', '-l'], shell=False) # print(result) # subprocess.check_call(["ls", "-l"]) # subprocess.check_call("exit 1", shell=True) # 好像沒Python廢棄了 subprocess.check_output(["echo", "Hello World!"], shell=False) subprocess.check_output("exit 1", shell=True) # 2、執行復雜的系統相關命令 # 1)切換目錄再執行命令 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',) # 2)有多行且複雜的命令使用三個接口 # obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # obj.stdin.write("print(1)\n") # 傳命令接口 # obj.stdin.write("print(2)") # obj.stdin.close() # # cmd_out = obj.stdout.read() # 讀接口 # obj.stdout.close() # cmd_error = obj.stderr.read() # 讀錯誤接口 # obj.stderr.close() # # print(cmd_out) # print(cmd_error) # 3)一次讀輸出 # obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # obj.stdin.write("print(1)\n") # obj.stdin.write("print(2)") # # out_error_list = obj.communicate() # print(out_error_list) # 4)簡單寫法 # obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # out_error_list = obj.communicate('print("hello")') # print(out_error_list)