shell_execute.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os, io, sys, platform, shutil, time, subprocess, json, datetime
  2. # 执行Shell命令,处理报错和超时,并有返回值
  3. def execute_Command(cmd_str, timeout=60, timeinner=3, retry=True):
  4. print(cmd_str)
  5. time_out = 0
  6. status = False
  7. while time_out < timeout:
  8. out_str = subprocess.getstatusoutput(cmd_str)
  9. print(out_str)
  10. if out_str[0] == 0 and out_str[1].find('ERROR') == -1 and out_str[1].find('error') == -1:
  11. status = True
  12. print('\nExecute successfully')
  13. break
  14. elif retry:
  15. print('\nTry again')
  16. time.sleep(timeinner)
  17. time_out = time_out + timeinner
  18. else:
  19. time_out = timeout
  20. if not status:
  21. print('\n此次任务执行有异常,请仔细排查')
  22. # 执行Shell命令,处理报错和超时,并有返回值
  23. def execute_CommandReturn(cmd_str, timeout=30, timeinner=3):
  24. print(cmd_str)
  25. time_out = 0
  26. while time_out < timeout:
  27. out_str = subprocess.getstatusoutput(cmd_str)
  28. print(out_str)
  29. if out_str[0] == 0 and out_str[1].find('ERROR') == -1 and out_str[1].find('error') == -1:
  30. # 去掉\n和"
  31. # 返回值是元组,不能修改,需要赋值给变量
  32. temp_str = out_str[1]
  33. temp_str = temp_str.strip('\n')
  34. temp_str = temp_str.strip('"')
  35. time_out = timeout
  36. return temp_str
  37. else:
  38. time.sleep(timeinner)
  39. time_out = time_out + timeinner
  40. print('\n此次任务执行失败,请根据下面错误原因排查:')
  41. print(out_str)