将标准输出和标准错误输出都写入文件
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)
标签:shell,run,subprocess,command,result,file,output From: https://www.cnblogs.com/testzcy/p/18237591