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

用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脚本代码如下

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)

使用效果


相关推荐
BuLingLings42 分钟前
vue3+flask+sqlite前后端项目实战
python·sqlite·flask
什码情况1 小时前
星际篮球争霸赛/MVP争夺战 - 华为OD机试真题(A卷、Java题解)
java·数据结构·算法·华为od·面试·机试
AA-代码批发V哥1 小时前
正则表达式: 从基础到进阶的语法指南
java·开发语言·javascript·python·正则表达式
字节高级特工1 小时前
【C++】”如虎添翼“:模板初阶
java·c语言·前端·javascript·c++·学习·算法
晴天下小雨o1 小时前
排序算法总结
java·算法·排序算法
曼岛_1 小时前
[Java实战]Spring Boot 整合 Redis(十八)
java·spring boot·redis
向哆哆1 小时前
Netty在Java网络编程中的应用:实现高性能的异步通信
java·网络·php
缘友一世1 小时前
Pytorch常用统计和矩阵运算
人工智能·pytorch·python
alpha xu1 小时前
Qwen智能体qwen_agent与Assistant功能初探
数据库·人工智能·python·oracle·智能体·千问agent
程序员爱钓鱼2 小时前
循环语句:for、range -《Go语言实战指南》
java·数据结构·算法