笔记-用Python脚本启停JAR程序

devtools/2024/10/22 16:30:36/

python_0">用Python脚本启停JAR程序,需要用到python中的以下内置模块

subprocess 是 Python 的一个标准库模块,用于在新进程中执行子命令,获取子进程的输入/输出/错误以及返回码等os 是 Python 的一个标准库模块,它提供了与操作系统交互的功能。通过 os 模块,Python 程序可以访问操作系统提供的底层功能,如文件和目录管理、环境变量、系统命令执行、进程管理等sys模块是Python标准库中的一个内置模块,它提供了与Python解释器和运行环境相关的功能。具体来说,sys模块包含了一系列用于与Python解释器交互的函数和变量,这些函数和变量可以用于获取命令行参数、控制程序的执行、管理模块和包、处理异常等time 是 Python 的一个标准库模块,它提供了各种时间相关的函数。time 模块主要用于时间的访问和转换,包括时间戳、结构化时间、字符串时间等signal模块是Python的一个标准库模块,它用于处理与操作系统相关的信号。信号(signal)是一种异步通知机制,用于通知进程某个事件的发生。在Python中,signal模块允许开发者注册信号处理函数,以便在接收到特定信号时执行相应的操作。
signal模块提供了一些常用的信号和函数,例如:
SIGALRM:闹钟信号,当使用signal.alarm()设置的定时器超时时发送。
SIGTERM:终止信号,用于请求程序正常终止。
SIGQUIT:终端退出信号,通常用于在终端中强制退出程序。
signal.alarm(time):设置一个定时器,在time秒后发送SIGALRM信号。
signal.signal(signum, handler):注册一个信号处理函数handler,用于处理指定的信号signum。
使用signal模块,开发者可以优雅地处理各种操作系统信号datetime 是 Python 的一个标准库模块,它提供了日期和时间相关的类。这个模块主要用于处理日期和时间数据,如获取当前日期和时间、日期的加减、格式化日期和时间等

python_24">详细python脚本代码如下

python">import subprocess  
import os  
import sys  
import time  
import signal
from datetime import datetime  # 获取当前日期和时间  
now = datetime.now()  
# 格式化日期和时间为字符串  
formatted_now = now.strftime("%Y%m%d%H%M%S")  # JAR文件的路径(相对于脚本的路径)  
JAR_PATH = 'graph-note-app.jar'  
# 用于保存JVM进程PID的文件路径  
PID_FILE = 'app.pid'  def start_app():  if is_app_running():  print("App is already running.")  return  # 定义日志文件路径  stdout_log_file = 'app_stdout'+formatted_now+'.log'  stderr_log_file = 'app_stderr'+formatted_now+'.log'  # 确保日志文件不存在,或者清空它们  with open(stdout_log_file, 'w') as f:  f.truncate(0)  with open(stderr_log_file, 'w') as f:  f.truncate(0)  cmd = ['java', '-jar', JAR_PATH]  process = subprocess.Popen(cmd, stdout=open(stdout_log_file, 'a'), stderr=open(stderr_log_file, 'a'))  with open(PID_FILE, 'w') as f:  f.write(str(process.pid))  print(f"App started with PID: {process.pid}")  def stop_app():  if not is_app_running():  print("App is not running.")  return  with open(PID_FILE, 'r') as f:  pid = int(f.read().strip())  try:  # 尝试优雅地终止进程  os.kill(pid, signal.SIGTERM)  time.sleep(2)  # 等待进程终止  if is_app_running():  # 如果进程仍然存在,则强制杀死它  os.kill(pid, signal.SIGKILL)  print(f"App with PID {pid} forcibly killed.")  else:  print(f"App with PID {pid} stopped.")  except OSError as e:  print(f"Error stopping app: {e}")  try:  os.remove(PID_FILE)  except FileNotFoundError:  pass  def is_app_running():  if not os.path.exists(PID_FILE):  return False  with open(PID_FILE, 'r') as f:  pid = int(f.read().strip())  try:  os.kill(pid, 0)  # 尝试向进程发送0信号(不会实际终止进程)  except OSError:  return False  return True  def status_app():  if is_app_running():  print("App is running.")  else:  print("App is not running.")  def show_help():  print("Available commands:")  print("start\t- Start the JAR application.")  print("stop\t- Stop the JAR application if it's running.")  print("status\t- Check if the JAR application is running.")  print("help\t- Show this help message.")  if __name__ == "__main__":  if len(sys.argv) < 2:  show_help()  sys.exit(1)  command = sys.argv[1].lower()  if command == 'start':  start_app()  elif command == 'stop':  stop_app()  elif command == 'status':  status_app()  elif command == 'help':  show_help()  else:  print(f"Unknown command: {command}")  show_help()  sys.exit(1)

使用效果

在这里插入图片描述
在这里插入图片描述


http://www.ppmy.cn/devtools/30654.html

相关文章

设计模式: 模板模式

目录 一&#xff0c;模板模式 二&#xff0c;特点 三&#xff0c;组成部分 四&#xff0c;实现步骤 五&#xff0c;案例 一&#xff0c;模板模式 模板模式&#xff08;Template Pattern&#xff09;是一种行为型设计模式&#xff0c;它在超类中定义了一个算法的骨架&#…

C++基础—模版

C模板是C语言中实现泛型编程的核心机制&#xff0c;它允许程序员定义通用的代码框架&#xff0c;这些框架在编译时可以根据提供的具体类型参数生成相应的特定类型实例。 泛型编程的特点代码复用和安全性! 模板主要分为两大类&#xff1a;函数模板和类模板。 函数模板 基本语…

SpringBoot-@Transactional注解失效

Transactional注解失效 Transactional失效场景 以下是一些常见导致Transactional注解失效的场景&#xff0c;配合相应的Java代码演示&#xff1a; 1、方法修饰符非公开&#xff08;非public&#xff09; Transactional注解失效的原因在于Spring事务管理器如何实现对事务的代…

springboot2.6.7集成springfox3.0.0

springboot2.6.7集成springfox3.0.0 1. pom配置2. 增加swagger自动配置类3. 配置修改4. 自动配置类增加以下内容参考 1. pom配置 <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency><groupId>io.springfox</g…

机器学习入门之非监督学习和半监督学习

文章目录 非监督学习半监督学习机器学习的核心价值 非监督学习 与监督学习相反&#xff0c;非监督学习的训练数据集是完全没有标签的数据&#xff0c;他本质上所做的工作都是聚类的 给定数据之后&#xff0c;聚类能从中学习到什么&#xff0c;就完全取决于数据本身的特性的&a…

上海计算机学会2022年4月月赛C++丙组T3平衡括号(简)

题目描述 给定一个只包含 ( 与 ) 的括号序列&#xff0c;请删除尽量少的括号&#xff0c;使它变成平衡的。平衡的定义如下&#xff1a; 空序列是平衡的&#xff1b;如果某个括号序列 s 是平衡的&#xff0c;那么 (s) 也是平衡的&#xff1b;如果某两个括号序列 s 与 t 都是平…

【机器学习】机器学习学习笔记 - 监督学习 - KNN线性回归岭回归 - 02

监督学习 KNN (k-nearest neighbors) KNN 是用 k 个最近邻的训练数据集来寻找未知对象分类的一种算法 from sklearn import neighbors# 分类 # 创建KNN分类器模型并进行训练 classifier neighbors.KNeighborsClassifier(num_neighbors, weightsdistance) classifier.fit(X,…

处理分支更新与pull操作

处理分支更新与pull操作 问题描述 There is no tracking information for the current branch. Please specify which branch you want to merge with. See git-pull(1) for details.git pull <remote> <branch> If you wish to set tracking information for th…