我需要帮助!
我有一些日志,从中需要解析/提取一些信息。这些日志适用于不同情况,并保存在不同的文件夹中。我制作了一些python脚本来提取我需要的信息,但是我想要的是能够提供文件夹/文件的位置作为脚本中的参数,这样我就不需要每次都复制并执行.py脚本了夹。代码部分看起来像这样,忽略所有这些初始化的var:
def peip(*args):
split_data = ''
split_data1 = ''
split_data2 = ''
split_data3 = ''
split_data4 = ''
split_data5 = ''
split_data6 = ''
split_data7 = ''
split_data8 = ''
split_data9 = ''
split_data10 = ''
split_data11 = ''
SPU = ''
Burst = ''
CountRTT_avrg = 0
output = []
Mbps = []
Total_Packets1 = []
output.append('Peip1 Pack., Peip2 Pack., Peip3 Pack., Peip4 Pack., Total Packets, Mbps, SPU Load(%), Average RTT(ms), Burst\n')
for arg in args:
print "another arg:", arg
if arg == 'putty_1_1.log':
with open ('putty_1_1' + '.log', mode='r') as a:
lines = a.readlines() #lines is list
for i, line in enumerate(lines):
if line.startswith('^C--'):
data = lines[i - 1].strip()
split_data = data.split()[4]
split_data1 = data.split()[6]
print 'PeipX Mbps:', split_data
print 'PeipX packets:', split_data1
elif arg == 'putty_1_2_rtt.log':
with open ('putty_1_2_rtt' + '.log', mode='r') as b:
lines1 = b.readlines() #lines is list
for i, line in enumerate(lines1):
if line.startswith('rtt'):
data = lines1[i].strip()
split_data2 = data.split('/')[4]
print 'avg rtt/peipX:', split_data2
# ...
# ...
# ...
# and at the end i have calling the function...
names = []
Num_of_input_logs = raw_input('Enter the number of input logs: ')
#print Num_of_input_logs
for z in range(0, int(Num_of_input_logs)):
Input_logs = raw_input('Enter the input logs one by one: ')
names.append(Input_logs)
print names
print z
peip(*names)
答案 0 :(得分:0)
您可能只想使用参数和argparse而不是交互式输入。
import argparse
import os
def peip(filenames):
for filename in filenames:
realname = os.path.realpath(filename)
basename = os.path.basename(filename) # to get the filename only
print(filename, basename, realname)
with open(realname) as f:
if basename == 'something.log':
pass # do things!
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('files', metavar='file', nargs='*')
args = ap.parse_args()
if not args.files:
ap.error('no files!')
peip(args.files)
还有一个随机示例...
$ python3 so51282670.py ../Pictures/*.jpg
../Pictures/citd.jpg citd.jpg /Users/akx/Pictures/citd.jpg
../Pictures/citd2.jpg citd2.jpg /Users/akx/Pictures/citd2.jpg
../Pictures/Goodboy.jpg Goodboy.jpg /Users/akx/Pictures/Goodboy.jpg
../Pictures/Prairie.jpg Prairie.jpg /Users/akx/Pictures/Prairie.jpg