工具开发背景:
将一个含有很多基站ip的文件拆分成多个batch文件。
$ cat Node_list | wc -l
3230
$python Generate_node_list.py -N 50 -F node_list
可将含有多个node Ip 的文件拆分成50个一组的新文件。
代码如下,文件为 Generate_node_list.py
#!/usr/bin/python
import sys, getopt
def GetOption(argv):
nodes_count = ''
nodes_file = ''
try:
opts, args = getopt.getopt(argv, "hN:F:",["Num=","File="])
except getopt.GetoptError:
print ('Error arg input -N ')
sys.exit(2)
for opt, arg in opts:
if opt == "-h":
print ('input python Generate_node_list.py -N ')
sys.exit()
elif opt in ("-N", "--Num"):
nodes_count = arg
elif opt in ("-F", "--File"):
nodes_file = arg
return ( nodes_file, nodes_count,)
if __name__ == '__main__':
option = GetOption(sys.argv[1:]) #指定外部输入的nodelist文件和每个文件含有的node数量
node_list_file, nodes_per_batch = option
nodes = open(node_list_file,'r')
nodelist = nodes.readlines()
nodelist_cp = nodelist[:] #拷贝node列表
num = 0
while num <= len(nodelist)/int(nodes_per_batch):
line = 0
for i in nodelist_cp:
batchfile = open('batch_' + str(num+1),'a+')
batchfile.write(i) #将node写入列表
line += 1
if line == int(nodes_per_batch):
for j in range(int(nodes_per_batch)):
nodelist_cp.pop(0) #将已经写入到batch文件的node从列表中移除
break
num += 1
print('The total number of nodes in this file is ' + str(line))