01 遇到的錯(cuò)誤
遇到錯(cuò)誤的源代碼如下:(修改后)
創(chuàng)新互聯(lián)建站專(zhuān)業(yè)為企業(yè)提供衛(wèi)東網(wǎng)站建設(shè)、衛(wèi)東做網(wǎng)站、衛(wèi)東網(wǎng)站設(shè)計(jì)、衛(wèi)東網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、衛(wèi)東企業(yè)網(wǎng)站模板建站服務(wù),十載衛(wèi)東做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
import time
from multiprocessing import Process
import json
from multiprocessing import Lock
def show():
with open(r'E:\text1\day36\ticket','r',encoding='utf-8') as f:
dit=json.load(f)
print('%s余票數(shù):\033[32m%s\033[0m' %(dit['place'],dit['余票']))
def buy(i,lock): # 必須傳入一個(gè)鎖的對(duì)象
lock.acquire()
time.sleep(0.5)
with open(r'E:\text1\day36\ticket','r',encoding='utf-8') as f:
dit = json.load(f)
if dit['余票']>0:
print('%s \033[32m購(gòu)票成功\033[0m' %i)
dit['余票']-=1
else:
print('%s \033[31m無(wú)余票\033[0m' %i)
time.sleep(0.1)
with open(r'E:\text1\day36\ticket','w',encoding='utf-8') as f:
json.dump(dit,f)
lock.release()
if __name__ =='__main__':
for i in range(10):
p=Process(target=show)
p.start()
lock=Lock() # 實(shí)例化一個(gè)鎖的對(duì)象
# lock.acquire()
# lock.release()
for i in range(10):
p=Process(target=buy,args=(i,lock))
p.start()
ticket-text文件`
{"place": "\u54c8\u5c14\u6ee8-->\u5317\u4eac", "\u4f59\u7968": 0}``
錯(cuò)誤1
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa8 in position 18: illegal multibyte sequence
錯(cuò)誤的原因:
gbk不能去解碼bytes類(lèi)型的數(shù)據(jù),非法多字節(jié)序列
解決方法:
with open(path,mode='r',encoding='utf-8') as f:
現(xiàn)在感覺(jué)是在不完全弄明白decode,encode之前,不要隨便的省略編碼類(lèi)型;
錯(cuò)誤2
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
錯(cuò)誤的原因:
期望雙引號(hào)中包含的屬性名稱(chēng) (double quotes 雙引號(hào))
解決的方法:
一般情況是不會(huì)出現(xiàn)這樣的情況的,因?yàn)橥ㄟ^(guò)json.dumps()向文件中寫(xiě)入str的類(lèi)型,再通過(guò)json.loads()來(lái)將文件中str的類(lèi)型轉(zhuǎn)換成原格式,是不會(huì)存在問(wèn)題的,
要注意的就是,json.dumps()寫(xiě)入的str字符串,字符串是用雙引號(hào)的(" "),所有要是自己寫(xiě)一個(gè)文件通過(guò)json.loads()/json.dumps()操作,將字符串用雙引號(hào)就好.