RPA 应用函数分享之 --- 通过 cmd 命令调用 java jar 包
下面分享几种调用 jar 包的方法:
# coding=utf-8
import os,shutil,sys,subprocess,time
#subprocess调用cmd命令,无数据交互,可以流程下发,调用结果采用java写本地文件python读取的方式
def use_jar_by_cmd():
cmd_shell = r'java -jar -Xmx1024m D:\ISearch\jar_lib\test.jar '#后面跟参数
subprocess.Popen(cmd_shell,shell=True,bufsize = 8192)
find_result()
write_log_to_excel()
def find_result():
sign_path = path+'result.finish'
while True:
time.sleep(60)
if os.path.exists(sign_path):
break
def write_log_to_excel():
result_path = path + 'result.log'
data_titles = ['处理类型','业务编号','处理结果']
data_values = []
with open(result_path,'r') as file:
try:
for line in file:
line = line.strip()
line = line.strip('\n')
if not line:
continue
else:
tmp_data = line.split(';')
if len(tmp_data) != 3:
continue
data_values.append(tuple(tmp_data))
except Exception as e:
pass
df = pd.DataFrame.from_records(data_values,columns = data_titles)
result_file_path = code_path + '\\' + result_file_name
df.to_excel(result_file_path,index=False)
#subprocess调用cmd命令,有数据交互,只可本地运行,不可以流程下发
def use_jar_by_cmd_another_two():
cmd_1 = 'd:'
cmd_2 = 'cd d:\Isearch'
cmd_3 = r'java -jar -Xmx1024m test.jar '#后面跟参数
p = subprocess.Popen(cmd_1+'&&'+ cmd_2+'&&'+ cmd_3,shell=True,bufsize = 8192,stdout = subprocess.PIPE)
p.wait()
out = p.stdout.readlines()
print(out)
if str(out[-1]).find('FINISHED')>-1:
print('success')
#os.popen调用cmd命令,不可以一条一条调用,每次路径为cmd默认路径
def use_jar_by_cmd_another():
responce = os.popen('ping www.baidu,com').read()
print(responce)
#python编写运行bat脚本的方式调用jar包
def use_jar_by_bat():
cmd_1 = 'd:'
cmd_2 = 'cd d:\Isearch'
cmd_3 = r'java -jar -Xmx1024m test.jar '#后面跟参数
create_script([cmd_1, cmd_2, cmd_3])
create_bat()
openfile(bat_path)
def create_script(cmd_list):
script_file = open(script_path,'w')
for cmd_str in cmd_list:
script_file.write(cmd_str)
script_file.write('\n')
script_file.close()
def create_bat():
bat_file = open(bat_path,'w')
bat_file.write('@echo off')
bat_file.write('\n')
bat_file.write(f'for /f "delims=" %%a in ({script_path}) do (')
bat_file.write('\n')
bat_file.write(' %%a')
bat_file.write('\n')
bat_file.write(')')
bat_file.write('\n')
bat_file.close()
def openfile(filePath):
os.startfile(filePath)