使用继承python34创建一个交互式命令循环 [英] Create an interactive command loop using inheritance python34
问题描述
我试图看看我可以如何构建一个脚本,我可以使用继承方法。我是相当新的python。我的问题是使用变量在一个类从另一个class-def。我最近刚刚了解了 super
函数,我不认为我使用它是正确的,因为它保持打印和重新计算的一切,它正在拉。
假设我有一堆消息在一个文本文件中,这些文件由逗号分隔,并给出了不同的信息。我想要能够获取该文本文件和...
- 能够读取以逗号(done) li>
- 告诉我每种类型的邮件有多少(已完成)
- 然后创建一个名为messages的类,
- 创建类在客户端和xls中打印和写入这些计算和变量(由于我的问题而部分完成)
- 创建类将xls转换为csv和kml(有些做)
这里是我正在使用的玩具结构
import bunch of stuff
data = [] #empty因为我们将数据存储到它
#读取CSV文件并返回作为行的列表
def read_csv_file(filename):
读取CSV文件并将其作为行列表返回
用于csv中的行.reader(open(filename)):
data.append(row)
返回数据
打开(path_in + data_file)as csvfile:
read_it = list (csv.reader(csvfile,delimiter =','))
#计算观察GPS命令的次数
def list_msg_type_countdata):
计数观察GPS命令的次数。
返回一个字典对象。
msg_count = dict()
数据行:
try:
msg_count [ row [0]] + = 1
,除了KeyError:
msg_count [row [0]] = 1
return msg_count
print(list_msg_type_count read_it))
print( - - - - - - - - - - - - )
类CreateWorkbook:
def openworkbook )
全局output_filename
output_filename = input('output filename:')
全局工作簿
workbook = xlsxwriter.Workbook(path_out + output_filename +'_'+ command_type +'。 xlsx')
self.worksheet = workbook.add_worksheet()
#formatting定义
全局粗体
bold = workbook.add_format({'bold':True})
全局date_format
date_format = workbook.add_format({'num_format':m / d / yyyy hh:mm:ss})
全局time_format
time_format = workbook.add_format num_format':hh:mm:ss})
def closeworkbook_gprmc(self,data):
print('closeworkbook')
来自process_msg1的数据
(i1,i2,i3)= messagetype.process_msg1(data)
#设置标题行
self.worksheet.write('A1','item1',bold)
self
self.worksheet.write('C1','item3',bold)
self.worksheet.autofilter('A1:C1' )#dropdown菜单为过滤创建
#创建一个For循环遍历XLS文件中的每一行,从第2行开始跳过标题
for r,row in enumerate(data ,start = 1):#你想在工作簿中开始打印结果
for c,col in enumerate(data):
self.worksheet.write_column(r,0,i1)
self.worksheet.write_column(r,1,i2)
self.worksheet.write_column(r,2,i3)
workbook.close()
f.close()
print('XLSX file named'+ output_filename +'_'+ command_type +'was created')
def closeworkbook_msg2(self,data):
#pull data_from process_msg2
(a1,i2,i3,i4)= messagetype.process_msg2(data)
#设置标题行
self.worksheet.write('A1','item1',bold)
self.worksheet.write('C1','item3',bold)
self.worksheet.write('C1',' 'item4',bold)
self.worksheet.autofilter('A1:C1')#dropdown菜单为过滤创建
#创建一个For循环遍历XLS文件中的每一行,从第2行开始跳过标题
for r,enumerate(data,start = 1)中的行:#where你想开始在工作簿中打印结果
for c,col in enumerate :
self.worksheet.write_column(r,2,i3)
self.worksheet.write_column(r,1,i2)
self.worksheet.write_column b $ b self.worksheet.write_column(r,3,i4)
workbook.close()
f.close()
print('XLSX file named'+ output_filename +'_' + command_type +'was created')
class ConvertFile
def convert2csv(self,data):
#设置包含xlsx文件的文件夹的路径
os.chdir(path_out)
#查找扩展名为.xlsx的文件
xlsx = glob.glob(output_filename +'_'+ command_type +'.xlsx')
#创建扩展名为.csv的输出文件名
csvs = [x.replace('。xlsx','。csv')for x in xlsx]
#的元组
in_out = zip(xlsx,csvs)
#循环遍历每个文件,从子进程调用in2csv实用程序
for xl,csv in in_out:
out = open(csv,'w')
command ='c:/ python34 / scripts / in2csv%s\\%s'%(path_out,xl)
proc = subprocess.Popen ,stdout = out)
proc.wait()
out.close()
print('CSV file named'+ output_filename +'_'+ command_type +'was created')
def convert2kml(self,data):
#输入文件名。
h = open(path_out + output_filename +'_'+ command_type +'.csv')
with h as csvfile2:
data2 = csv.reader(csvfile2,delimiter =',')
next(data2)
#打开要写入的文件。
g = open(output_filename +'_'+ command_type +'。kml','w')
g.write(<?xml version ='1.0'encoding ='UTF-8'? > \\\
)
g.write(< kml xmlns ='http://earth.google.com/kml/2.1'> \\\
)
g.write (< Document> \ n)
g.write(< name>+ output_filename +'_'+ command_type +'.kml'+< / name> \\\
)
for data in data2:
g.write(< Placemark> \\\
)
g.write(< TimeStamp>< when& 0])+< / when>< / TimeStamp> \\\
)
g.write(< Point> \\\
)
g.write( ;+ str(row [2])+,+ str(row [1])+< / coordinates> \\\
)
g.write(< / Point> n)
g.write(< / Placemark> \\\
)
g.write(< / Document> \\\
)
g.write(< / kml> \\\
)
g.close()
h.close()
print('and'+ output_filename +'_ '+ command_type +'。kml也创建了!)
class MessageType:
def process_msg1(self,data)
item1 = []
item2 = []
item3 = []
print('printing stuff')
for r in data:
if row [0 ] =='msg type1'
item1.append('calculations')
item2.append('calculations')
item3.append('calculated')
print计算完成')
return(array(item1),array(item2),array(item3))
def process_msg2(self,data)
item1 = []
item2 = []
item3 = []
item4 = []
print('printing stuff')
for r in data:
if row [0] =='msg type1'
item1.append('calculated')
item2.append('calculated')
item3.append )
item4.append('calculate')
print('calculate done')
return(array(item1),array(item2),array(item3),array(item4))
class PrintMSG(MessageType):
def process_msg1(self,data):
(i1,i2,i3)= super(PrintMSG,self).process_msg1 b $ b print('print'使用来自类Message'的变量的绘图)
def process_msg2(self,data):
(i1,i2,i3,i4) self).process_msg2(data)
print('printing plus plotting using variables from class Message')
#processing piece
keep_asking = True
同时keep_asking:
command_type = input(你想看什么消息类型?)
如果command_type =='msg type1':
createworkbook = CreateWorkbook createworkbook.openworkbook(data)
msg = MessageType()
print_msg = PrintMSG()
print_msg.process_msg1(data)
createworkbook.closeworkbook_msg1(data)
convert2csv数据)
convert2kml(data)
elif command_type =='msg type2':
createworkbook = CreateWorkbook()
createworkbook.openworkbook(data)
msg = MessageType )
print_msg = PrintMSG()
print_msg.process_msg2(data)
createworkbook.closeworkbook_msg2(data)
convert2csv(data)
convert2kml(data)
else
print(Invalid type:,command_type)
wannalook = input('想查看另一个消息或否?')
如果不是wannalook.startswith 'y'):
keep_asking = False
类定义
代码很大,有很多事情不能工作或者可以改进。作为开始,接受 CreateWorkbook
类。您需要始终使用 self
作为方法的第一个参数。为了能够在另一个方法中使用在另一个方法中定义的变量,你需要用 self作为前缀。
:
class CreateWorkbook:
def openworkbook(self,data):
self.output_filename = input filename:')
self.workbook = xlsxwriter.Workbook(path_out + output_filename +'_'+ command_type +'。xlsx')
self.worksheet = workbook.add_worksheet()
def closeworkbook_msg1(self,data):
#设置标题行
self.worksheet.write('A1','item1',bold)
self.worksheet.write 'b1','item2',bold)
self.worksheet.write('C1','item3',bold)
self.worksheet.autofilter('A1:C1')#dropdown menu created用于过滤
#创建一个For循环遍历XLS文件中的每一行,从第2行开始跳过标题
for r,row in enumerate(data,start = 1) :#你想在工作簿中开始打印结果
for c,col in enumerate(data):
self.worksheet.write_column(r,0,i1)
self.worksheet.write_column (r,1,i2)
self.worksheet.write_column(r,2,i3)
self.workbook.close()
print('XLSX file named'+ output_filename +'_ '+ command_type +'is created')
def closeworkbook_msg2(self,data):
#设置标题行
self.worksheet.write('A1'
self.worksheet.write('C1','item3',bold)
self.worksheet.write('B1','item2',bold) .worksheet.write('C1','item4',bold)
self.worksheet.autofilter('A1:C1')#为了过滤而创建的dropdown菜单
#创建一个For循环遍历XLS文件中的每一行,从第2行开始跳过标题
for r,enumerate(data,start = 1):#where你想在工作簿中开始打印结果
for c,col in enumerate(data):
self.worksheet.write_column(r,0,i1)
self.worksheet.write_column(r,1,i2)
self.worksheet。 write_column(r,2,i3)
self.worksheet.write_column(r,3,i4)
self.workbook.close()
print('XLSX file named'+ output_filename + _'+ command_type +'is created')
阅读csv
b $ b
这没什么意义:
f = open(path_in + data_file)
read_it = read_csv_file(path_in + data_file)
with f as csvfile:
readCSV = csv.reader(csvfile,delimiter =',')
我会把它解释为这样:
with open(path_in + data_file)as csvfile:
read_it = list(csv.reader(csvfile,delimiter =','))
I'm trying to see how I can structure a script in a way that I can use the inheritance method. I'm fairly new to python. And my problem is using variables in one class from another class-def. I just recently learned about the
super
function and I don't think I'm using it right because it keeps printing and recalculating everything that it's pulling from.Let's say I have a bunch of messages coming in a text file delimited by commas that give me different information. I want to be able to take that text file and...
- be able to read the content delimited by commas (done)
- tell me how many of each type of message there are (done)
- then create a class called messages that has defs for each type of message with its respective calculations and variables it creates in those instances (done)
- create class to print and write those calculations and variables in the client and xls (partially done due to my issue)
- create class to convert xls to csv and kml (somewhat done)
Here is a toy structure of what I'm working with
import bunch of stuff data = [] #empty because we will store data into it #Reads a CSV file and return it as a list of rows def read_csv_file(filename): """Reads a CSV file and return it as a list of rows.""" for row in csv.reader(open(filename)): data.append(row) return data with open(path_in + data_file) as csvfile: read_it = list(csv.reader(csvfile, delimiter=',')) #Counts the number of times a GPS command is observed def list_msg_type_countdata): """Counts the number of times a GPS command is observed. Returns a dictionary object.""" msg_count = dict() for row in data: try: msg_count[row[0]] += 1 except KeyError: msg_count[row[0]] = 1 return msg_count print(list_msg_type_count(read_it)) print ("- - - - - - - - - - - - -") class CreateWorkbook: def openworkbook(self, data): global output_filename output_filename = input('output filename:') global workbook workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx') self.worksheet = workbook.add_worksheet() #formatting definitions global bold bold = workbook.add_format({'bold': True}) global date_format date_format = workbook.add_format({'num_format': "m/d/yyyy hh:mm:ss"}) global time_format time_format = workbook.add_format({'num_format': "hh:mm:ss"}) def closeworkbook_gprmc(self, data): print('closeworkbook') #pull data from process_msg1 (i1, i2, i3) = messagetype.process_msg1(data) #sets up the header row self.worksheet.write('A1','item1',bold) self.worksheet.write('B1', 'item2',bold) self.worksheet.write('C1', 'item3',bold) self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook for c, col in enumerate(data): self.worksheet.write_column(r,0, i1) self.worksheet.write_column(r,1, i2) self.worksheet.write_column(r,2, i3) workbook.close() f.close() print('XLSX file named ' + output_filename + '_' + command_type +' was created') def closeworkbook_msg2(self, data): #pull data from process_msg2 (i1, i2, i3, i4) = messagetype.process_msg2(data) #sets up the header row self.worksheet.write('A1','item1',bold) self.worksheet.write('B1', 'item2',bold) self.worksheet.write('C1', 'item3',bold) self.worksheet.write('C1', 'item4',bold) self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook for c, col in enumerate(data): self.worksheet.write_column(r,0, i1) self.worksheet.write_column(r,1, i2) self.worksheet.write_column(r,2, i3) self.worksheet.write_column(r,3, i4) workbook.close() f.close() print('XLSX file named ' + output_filename + '_' + command_type + ' was created') class ConvertFile def convert2csv(self, data): # set path to folder containing xlsx files os.chdir(path_out) # find the file with extension .xlsx xlsx = glob.glob(output_filename + '_' + command_type + '.xlsx') # create output filenames with extension .csv csvs = [x.replace('.xlsx','.csv') for x in xlsx] # zip into a list of tuples in_out = zip(xlsx,csvs) # loop through each file, calling the in2csv utility from subprocess for xl,csv in in_out: out = open(csv,'w') command = 'c:/python34/scripts/in2csv %s\\%s' % (path_out,xl) proc = subprocess.Popen(command,stdout=out) proc.wait() out.close() print('CSV file named ' + output_filename + '_' + command_type + ' was created') def convert2kml(self, data): #Input the file name. h = open(path_out + output_filename + '_' + command_type + '.csv') with h as csvfile2: data2 = csv.reader(csvfile2,delimiter=',') next(data2) #Open the file to be written. g = open(output_filename + '_' + command_type +'.kml','w') g.write("<?xml version='1.0' encoding='UTF-8'?>\n") g.write("<kml xmlns='http://earth.google.com/kml/2.1'>\n") g.write("<Document>\n") g.write(" <name>" + output_filename + '_' + command_type + '.kml' +"</name>\n") for row in data2: g.write(" <Placemark>\n") g.write("<TimeStamp><when>" + str(row[0]) + "</when></TimeStamp>\n") g.write(" <Point>\n") g.write(" <coordinates>" + str(row[2]) + "," + str(row[1]) + "</coordinates>\n") g.write(" </Point>\n") g.write(" </Placemark>\n") g.write("</Document>\n") g.write("</kml>\n") g.close() h.close() print('and ' + output_filename + '_' + command_type +'.kml was created,too!') class MessageType: def process_msg1(self,data) item1 = [] item2 = [] item3 = [] print('printing stuff') for r in data: if row[0] == 'msg type1' item1.append('calculations') item2.append('calculations') item3.append('calculations') print('calculations done') return(array(item1),array(item2),array(item3)) def process_msg2(self,data) item1 = [] item2 = [] item3 = [] item4 = [] print('printing stuff') for r in data: if row[0] == 'msg type1' item1.append('calculations') item2.append('calculations') item3.append('calculations') item4.append('calculations') print('calculations done') return(array(item1),array(item2),array(item3),array(item4)) class PrintMSG(MessageType): def process_msg1(self, data): (i1, i2, i3) = super(PrintMSG, self).process_msg1(data) print('printing plus plotting using variables from class Message') def process_msg2(self, data): (i1, i2, i3,i4) = super(PrintMSG, self).process_msg2(data) print('printing plus plotting using variables from class Message') #processing piece keep_asking = True while keep_asking: command_type = input("What message type do you want to look at?") if command_type == 'msg type1': createworkbook = CreateWorkbook() createworkbook.openworkbook(data) msg = MessageType() print_msg = PrintMSG() print_msg.process_msg1(data) createworkbook.closeworkbook_msg1(data) convert2csv(data) convert2kml(data) elif command_type == 'msg type2': createworkbook = CreateWorkbook() createworkbook.openworkbook(data) msg = MessageType() print_msg = PrintMSG() print_msg.process_msg2(data) createworkbook.closeworkbook_msg2(data) convert2csv(data) convert2kml(data) else: print("Invalid type:", command_type) wannalook = input('Want to look at another message or no?') if not wannalook.startswith('y'): keep_asking = False
解决方案Class definition
The code is kind of big and there are many things that do not work or could be improved. As a starter, take the class
CreateWorkbook
. You need always useself
, as the first argument for methods. (There are a few exceptions but they are not relevant here.) To be able to use variables defined in one method in another, you need to prefix them withself.
:class CreateWorkbook: def openworkbook(self, data): self.output_filename = input('output filename:') self.workbook = xlsxwriter.Workbook(path_out + output_filename + '_' + command_type +'.xlsx') self.worksheet = workbook.add_worksheet() def closeworkbook_msg1(self, data): #sets up the header row self.worksheet.write('A1','item1',bold) self.worksheet.write('B1', 'item2',bold) self.worksheet.write('C1', 'item3',bold) self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook for c, col in enumerate(data): self.worksheet.write_column(r,0, i1) self.worksheet.write_column(r,1, i2) self.worksheet.write_column(r,2, i3) self.workbook.close() print('XLSX file named ' + output_filename + '_' + command_type +' was created') def closeworkbook_msg2(self, data): #sets up the header row self.worksheet.write('A1','item1',bold) self.worksheet.write('B1', 'item2',bold) self.worksheet.write('C1', 'item3',bold) self.worksheet.write('C1', 'item4',bold) self.worksheet.autofilter('A1:C1') #dropdown menu created for filtering # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers for r, row in enumerate(data, start=1): #where you want to start printing results inside workbook for c, col in enumerate(data): self.worksheet.write_column(r,0, i1) self.worksheet.write_column(r,1, i2) self.worksheet.write_column(r,2, i3) self.worksheet.write_column(r,3, i4) self.workbook.close() print('XLSX file named ' + output_filename + '_' + command_type + ' was created')
Reading csv
This doesn't make much sense:
f = open(path_in + data_file) read_it = read_csv_file(path_in + data_file) with f as csvfile: readCSV = csv.reader(csvfile,delimiter=',')
I would interpret it as something like this:
with open(path_in + data_file) as csvfile: read_it = list(csv.reader(csvfile, delimiter=','))
这篇关于使用继承python34创建一个交互式命令循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!