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

使用效果


相关推荐
goxingman2 分钟前
关于使用idea打包的时候报错,Maven提示乱码java: �Ҳ�������
java·maven·intellij-idea
Chasing__Dreams17 分钟前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas
彭泽布衣1 小时前
python2.7/lib-dynload/_ssl.so: undefined symbol: sk_pop_free
python·sk_pop_free
邓不利东1 小时前
Spring中过滤器和拦截器的区别及具体实现
java·后端·spring
喜欢吃豆2 小时前
从零构建MCP服务器:FastMCP实战指南
运维·服务器·人工智能·python·大模型·mcp
草履虫建模2 小时前
Redis:高性能内存数据库与缓存利器
java·数据库·spring boot·redis·分布式·mysql·缓存
苹果醋32 小时前
Vue3组合式API应用:状态共享与逻辑复用最佳实践
java·运维·spring boot·mysql·nginx
一个处女座的测试2 小时前
Python语言+pytest框架+allure报告+log日志+yaml文件+mysql断言实现接口自动化框架
python·mysql·pytest
nananaij2 小时前
【Python基础入门 re模块实现正则表达式操作】
开发语言·python·正则表达式
Micro麦可乐2 小时前
Java常用加密算法详解与实战代码 - 附可直接运行的测试示例
java·开发语言·加密算法·aes加解密·rsa加解密·hash算法