前言
本篇和大家分享的是使用python简化对jar包操作命令,封装成简短关键字或词,达到操作简便的目的。最近在回顾和构思shell脚本工具,后面一些文章应该会分享shell内容,希望大家继续关注。
- 获取磁盘中jar启动包
- 获取某个程序进程pid
- 自定义jar操作命令
获取磁盘中jar启动包
这一步骤主要扫描指定磁盘中待启动的jar包,然后获取其路径,方便后面操作java命令:
#获取磁盘中jar启动包
def find_file_bypath(strDir):
filelist = os.listdir(strDir)
for file in filelist:
if os.path.isdir(strDir + "/" + file):
find_file_bypath(strDir + "/" + file)
else:
if(file.find(".jar") >= 0):
fileInfo = MoFileInfo(file,strDir + "/" + file)
all_list.append(fileInfo)
这个递归获取路径就不多说了,可以参考前一篇文章
获取某个程序进程pid
在linux中获取某个程序pid并打印出来通常的命令是:
1 ps -ef | grep 程序名字
在py工具中同样用到了grep命令,通过执行linux命令获取相对应的pid值:
#获取pid
def get_pid(name):
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
print(response)
return response
这里直接取的第一个值,因为上面第一节已经能够定位到程序jar包的名字,所以获取pid很容易
自定义jar操作命令
自定义其实就是用我们随便定义的单词或关键字来代替jar包操作命令,这里我封装了有5种,分别如下:
- nr:nohup java -jar {} 2>&1 &
- r:java -jar {}
- k:kill -9 {}
- d:rm -rf {}
- kd:kill -9 {}
{}代表的是pid和jar包全路径,相关代码:
#执行命令
'''
想要学习Python?Python学习交流群:1004391443满足你的需求,资料都已经上传群文件,可以自行下载!
'''
def exec_file(index):
try:
if(index = 0):
fileInfo = MoFileInfo(file,strDir + "/" + file)
all_list.append(fileInfo)
def show_list_file():
for index,x in enumerate(all_list):
print("{}. {}".format(index,x.name))
#获取pid
def get_pid(name):
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
print(response)
return response
#执行命令
def exec_file(index):
try:
if(index 0) else "/root/job"
#获取运行包
find_file_bypath(strDir)
#展示运行包
show_list_file()
#选择运行包
strIndex = raw_input("请选择要运行的编号:\r\n")
#执行命令
exec_file(strIndex)