一、python 执行shell 实时打印到屏幕上
from subprocess import Popen, PIPE, STDOUT move_data = "cmd_val" def exec_command(command): move_path = Popen(command, stdout=PIPE, stderr=STDOUT, encoding='utf-8', shell=True) with move_path.stdout: for line in iter(move_path.stdout.readline, b''): if len(line) > 3: print(line.encode().strip()) else: break exitcode = move_path.wait() return exitcode y = exec_command(move_data) print('运行结果:') print(y)
二、python 执行shell 不需要打印到屏幕上,只获取执行结果
import subprocess shell_cmd = "cmd_val" return_cmd = subprocess.run(shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8',shell=True) if return_cmd.returncode == 0: print('命令成功执行') # 还可以获取执行结果 ret_val = return_cmd.stdout else: print('命令执行失败') sys.exit(1)
标签:move,shell,stdout,python,cmd,subprocess,print,日志 From: https://www.cnblogs.com/zhangweimee/p/16598547.html