笔记-用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)

使用效果


相关推荐
小巫编程室9 分钟前
我造了一个 Java 能力包:让 AI 直接调用你的业务代码
java·前端·后端
深入云栈1 小时前
Netty 4.2.x 源码深度解析 (二十四):池化内存分配 —— PoolArena、PoolChunk 与 PoolSubpage
java·后端·架构
惜.己2 小时前
Java结合idea简单使用Playwright
java·开发语言·自动化
Vex2une3 小时前
JDK 8 下载安装与环境变量配置完整指南(Windows新手图文教程)
java·windows·环境配置·环境变量·jdk8·jdk下载安装·java入门教程
文丑颜不良啊4 小时前
LeetCode3281~3300题目解析
java·leetcode
nice_lcj5205 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
SimonKing6 小时前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
艾莉丝努力练剑6 小时前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
kyle~6 小时前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
aiotto资源分享6 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror