网络编程
位置:首页>> 网络编程>> Python编程>> python实现超市扫码仪计费

python实现超市扫码仪计费

作者:_从未止步  发布时间:2023-01-11 03:53:31 

标签:python,扫码仪

python实现超市扫码仪计费的程序主要是使用超市扫码仪扫商品的条形码,读取商品信息,实现计费功能。主要用到的技术是串口通信,数据库的操作,需要的环境包括:python环境,mysql,python库(serial,MySQLdb)等等。

这个程序的主要过程是:使用扫码仪扫描商品条形码,通过串口通信获取商品条形码,通过该条形码获取商品信息,显示该商品信息并统计总费用。其中商品信息保存在数据库中,可事先导入或者手动导入商品信息,而我的在这里是事先导入的(也可以边扫边倒入信息),导入到数据库中的信息如下:

python实现超市扫码仪计费

程序代码如下:


#coding:utf8

import serial
import MySQLdb

ser = serial.Serial('COM5',9600)

#获取一行信息
def recv(serial):
data = ''
while serial.inWaiting() > 0:
 data += serial.read(1)

return data

def GetInfo(db,data):
data = data[0:-1] #最后面有一个空格,需要去掉,否则会影响读数据库
print data
ret = 0.0
try:
 cur = db.cursor()
 sql="set names utf8" #这一条语句是告诉数据库编码方式为 utf8
 cur.execute(sql)

sql = "select * from productinfo where code=%s"%(data)
 #print sql
 cur.execute(sql)
 #sql = "select * from productinfo where(code=%s)"
 #cur.execute(sql,data)  
 results = cur.fetchall()
 #print results
 for row in results:
  code = row[0]
  #print code
  price = row[1]
  #print price
  info = row[2]
  #print info
  ret = price
  #解析出来的信息可能为中文,直接print肯定是不行的,需要转化为windows下的GBK编码
  print 'coding=',row[0],'price=',row[1],'info=',info.decode('UTF-8').encode('GBK')    
except:
 print 'it has no infomation about %s'%(data)

return ret

db = MySQLdb.connect('localhost','root','',"zou",3306,'utf8')
cursor = db.cursor()

#cursor.execute("DROP TABLE IF EXISTS productinfo")

'''''
sql="""CREATE TABLE productinfo(
 code CHAR(18),
 price double(9,2),
 info CHAR(25))"""
cursor.execute(sql)
'''

sum = 0.0  
while True:
data = recv(ser)
if data != '':
 #print data
 sum += GetInfo(db,data)
 print '总付款:',sum

db.close()
ser.close()

由于刚刚开始学习python,所以代码规范上做的还不是很好,希望大家多多指出,最后程序的运行如下:

python实现超市扫码仪计费

其中我的程序中可以使用中文(刚刚开始不是显示?就是显示乱码),这个问题我在前面的博客中谈论过,需要处理数据库以及从数据库读取的数据的编码方式。若是大家看出什么错误或是有意见的话,欢饮大家留言。

来源:https://blog.csdn.net/zr1076311296/article/details/51759480

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com