python 执行shell 日志 输出

一、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)

 

posted @ 2022-08-18 14:16  醉城、  阅读(717)  评论(0编辑  收藏  举报