python实现批处理文件
本文实例为大家分享了python实现批处理文件的具体代码,供大家参考,具体内容如下
Windows下的bat,linux下的shell用来做批处理都很好用,可惜不通用
用Python来做就简单多了,不过一条条写代码来调用系统命令也够烦的了
程序员都很懒,不愿做机械无谓的重复性工作,干脆自己实现一个.
用法超级简单,默认会执行一个自定义的batch.json,按顺序一条条执行其中的步骤
{"steps":
[
{"step":"df-h","desc":"displaydiskspaceusage"},
{"step":"date","desc":"displaythecurrentdater"},
{"step":"time","desc":"displaythecurrenttime"}
]
}
用法:
pythonbatch.py
当然也可以指定不同的步骤文件,例如
pythonbatch.pyxxx.json
运行结果以markdown形式输出,例如
$pythonbatch.py Usage:pythonbatch.pynote:executethebatch.jsonbydefault #Executebatch.jsonbegin --------------------------- ##Willexecute3steps ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 0.[df-h]:displaydiskspaceusage 1.[date]:displaythecurrentdater 2.[time]:displaythecurrenttime *0.[df-h]:displaydiskspaceusage FilesystemSizeUsedAvailCapacityiusedifree%iusedMountedon /dev/disk1233Gi208Gi24Gi90%54622825636469490%/ devfs329Ki329Ki0Bi100% *1.[date]:displaythecurrentdater ThuMar322:50:21CST2016 *2.[time]:displaythecurrenttime real0m0.001s user0m0.000s sys0m0.000s ##Donethefollowingsteps ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 0.[df-h]:displaydiskspaceusage 1.[date]:displaythecurrentdater #Executebatch.jsonend.
Python源代码如下,希望有人能用得上
'''
likebatfile,executethestepsinbatch.json
'''
importos,sys,subprocess
importtime,thread
importcodecs
importjson
fromdatetimeimportdatetime
fromsubprocessimportcall
frompprintimportpprint
defexecute_json(json_file):
print"#Execute{0}begin\n---------------------------".format(json_file)
json_data=open(json_file)
data=json.load(json_data)
cnt=len(data['steps'])
i=0
print"\n##Willexecute{0}steps\n~~~~~~~~~~~~~~~~~~~~~~~~~~~".format(cnt)
foriinrange(0,cnt):
print"{0}.[{1}]:{2}".format(i,data['steps'][i]['step'],data['steps'][i]['desc'])
#pprint(data)
#print("cnt=",cnt)
foriinrange(0,cnt):
cmd=data['steps'][i]['step']
desc=data['steps'][i]['desc']
print"\n*{0}.[{1}]:{2}".format(i,cmd,desc)
if(cmd.startswith('cd')):
cmd=cmd.replace("cd","")
os.chdir(cmd)
else:
ret=os.system(cmd)
if(ret!=0):
print"Encountererrorofstep{0}.{1},errorcode={2}".format(i,cmd,ret)
break
print"\n##Donethefollowingsteps\n~~~~~~~~~~~~~~~~~~~~~~~~~~~"
forjinrange(0,i):
print"{0}.[{1}]:{2}".format(j,data['steps'][j]['step'],data['steps'][j]['desc'])
json_data.close()
print"#Execute{0}end.".format(json_file)
if__name__=="__main__":
argc=len(sys.argv)
step_file='batch.json'
if(argc>1):
idx=1
while(idx".format(sys.argv[0])
print"note:executethebatch.jsonbydefault"
execute_json(step_file)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。