demo01.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import subprocess
  2. from datetime import datetime
  3. # 获取当前日期,并格式化为字符串
  4. now = datetime.now()
  5. date_str = now.strftime("%Y-%m-%d")
  6. # 定义日志文件名
  7. log_file = f"script_output_{date_str}.log"
  8. n1 = 1
  9. n2 = 5
  10. # 定义Shell脚本的路径
  11. script1_path = "./script1.sh"
  12. script2_path = "./script2.sh"
  13. # 打开日志文件准备写入
  14. with open(log_file, 'w') as f:
  15. # 调用script1.sh,不使用shell=True
  16. result1 = subprocess.run([script1_path, str(n1), str(n2)], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  17. text=True)
  18. # 检查script1.sh的返回码,并写入输出到日志文件
  19. if result1.returncode == 0:
  20. print("script1.sh 执行成功")
  21. f.write(f"--- script1.sh 输出 ---\n{result1.stdout}\n")
  22. # 调用script2.sh,同样不使用shell=True
  23. result2 = subprocess.run([script2_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  24. # 检查script2.sh的返回码,并写入输出到日志文件
  25. if result2.returncode == 0:
  26. print("script2.sh 执行成功")
  27. f.write(f"--- script2.sh 输出 ---\n{result2.stdout}\n")
  28. else:
  29. print("script2.sh 执行失败")
  30. f.write(f"--- script2.sh 错误输出 ---\n{result2.stderr}\n")
  31. else:
  32. print("script1.sh 执行失败")
  33. f.write(f"--- script1.sh 错误输出 ---\n{result1.stderr}\n")