利用subprocess.run执行shell命令,并将结果日志写入文件

将标准输出和标准错误输出都写入文件

import subprocess

def execute_shell_command(command, output_file):
    with open(output_file, 'w') as file:
        result = subprocess.run(command, stdout=file, stderr=subprocess.STDOUT,shell=True)
    print("Command return value:", result.returncode)

command = "bash /home/zcy/download/temp2.sh"
output_file = "output.log"

# 执行shell命令,并将标准输出和标准错误写入同一个文件
execute_shell_command(command, output_file)

将标准错误输出重定向到标准输出

import subprocess

def execute_shell_command(command):
    result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True)
    print("Command return value:", result.returncode)
    print(result.stdout.decode())

command = "bash /home/zcy/download/temp2.sh"
output_file = "output.log"

execute_shell_command(command)

 

posted on 2024-06-07 17:25  我和你并没有不同  阅读(10)  评论(0编辑  收藏  举报