首頁  >  文章  >  後端開發  >  python實現超市掃碼儀計費

python實現超市掃碼儀計費

不言
不言原創
2018-06-01 15:16:352163瀏覽

這篇文章主要為大家詳細介紹了python實現超市掃碼儀計費,具有一定的參考價值,感興趣的小伙伴們可以參考一下

python實現超市掃碼儀計費的程序主要是使用超市掃碼儀掃商品的條碼,讀取商品訊息,實現計費功能。主要用到的技術是串列埠通信,資料庫的操作,需要的環境包括:python環境,mysql,python函式庫(serial,MySQLdb)等等。

這個程式的主要過程是:使用掃碼儀掃描商品條碼,透過串口通訊取得商品條碼,透過該條碼取得商品訊息,顯示該商品資訊並統計總費用。其中商品資訊保存在資料庫中,可事先導入或手動導入商品信息,而我的在這裡是事先導入的(也可以邊掃邊倒入信息),導入到數據庫中的信息如下:

#程式碼如下:

#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實作計算圓周率π的值到任意位元的方法範例

python實作簡單淘寶秒殺功能

以上是python實現超市掃碼儀計費的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn