python3-模拟ATM_shopping

Posted shangshanyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3-模拟ATM_shopping相关的知识,希望对你有一定的参考价值。

一、readme

一、功能说明
环境:python3
功能:模拟银行ATM及购物商城等功能!
目的:study
注意:如果在Windows下开发并运行后移植到Linux中,需要删除每个目录中的缓存目录(__pycache__)。
二、目录结构
atm_shopping
|-- bank#ATM程序
|   |-- bin#程序入口
|   |   |-- atm_bank.py#ATM后台
|   |   |-- atm.py#ATM
|   |   `-- __init__.py
|   |-- func#功能函数
|   |   |-- function.py
|   |   |-- function.pyc
|   |   |-- __init__.py
|   |   |-- __init__.pyc
|   |   |-- logger.py
|   |   `-- logger.pyc
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- log用户日志
|   |   `-- __init__.py
|   |-- user_data#用户账户信息
|   |   |-- 123.pkl
|   |   `-- __init__.py
|   `-- user_login#ATM登陆认证
|       |-- __init__.py
|       |-- __init__.pyc
|       |-- login.py
|       `-- login.pyc
|-- __init__.py
`-- shopping#购物程序
    |-- bin#程序入口
    |   |-- goods_put_or_off.py#商品上下架
    |   |-- __init__.py
    |   |-- shopping.py#购物
    |   `-- user_set.py#账户设置
    |-- func
    |   |-- function.py#功能函数
    |   `-- __init__.py
    |-- goods#
    |   |-- goods.pkl#商品
    |   `-- __init__.py
    |-- __init__.py
    |-- log
    |   |-- __init__.py
    |   `-- shopping_log.txt#购物日志
    `-- user_login
        |-- login.py#购物登陆认证
        |-- user_create.py
        |-- user_info_all.bak
        |-- user_info_all.dat
        `-- user_info_all.dir

三、使用事例
1)、银行开户
C:\Python36\python3.exe F:/PyCharm/script/atm_shopping/bank/bin/atm_bank.py

        1:开户
        2:解锁或者冻结账户
        3:退出
        
请选择:1
----开始开户,请按提示输入---
请输入账号:123456
请输入姓名:映山红
请输入身份证号:332226199202011020
请输入额度:10000
请输入账户状态,默认为unlock,(Enter):
请输入密码:123456
开户成功:姓名[映山红],账号[123456],额度[10000]

        1:开户
        2:解锁或者冻结账户
        3:退出
        
请选择:3

Process finished with exit code 0
2)、ATM登陆
C:\Python36\python3.exe F:/PyCharm/script/atm_shopping/bank/bin/atm.py
---登陆认证---
请输入账号:123456
{‘account‘: ‘123456‘, ‘password‘: ‘123456‘, ‘time‘: 3, ‘money‘: 10000, ‘name‘: ‘映山红‘, ‘identified‘: ‘332226199202011020‘, 

‘status‘: ‘unlock‘, ‘edu‘: 10000}
请输入密码:123456
欢迎登陆

1:查询         2:提现
3:转账         4:还款
5:改密         6:退出

请选择:
3)购物商城用户创建
C:\Python36\python3.exe F:/PyCharm/script/atm_shopping/shopping/bin/user_set.py

        1:创建用户
        2:删除用户
        3:重置密码
        4:重置锁状态
        5:查看用户信息
        6:退出
        
请选择:1
请输入用户名(exit:退出):12345
请输入密码:12345
请输入用户名(exit:退出):exit
4)、商品上架
C:\Python36\python3.exe F:/PyCharm/script/atm_shopping/shopping/bin/goods_put_or_off.py
--商品上架--
请输入商品名称(退出:exit):榴莲
请输入商品价格:60
请输入商品名称(退出:exit):苹果
请输入商品价格:15
请输入商品名称(退出:exit):exit
5)、购物
C:\Python36\python3.exe F:/PyCharm/script/atm_shopping/shopping/bin/shopping.py
请输入用户名:123456
用户名不存在,请重新输入
请输入用户名:12345
请输入密码:12345
欢迎登陆
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
请选择:
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出
请选择:1
请选择要购买的商品编号:1
你选择的了:榴莲       价格为:60
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
请选择:
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出
请选择:1
请选择要购买的商品编号:2
你选择的了:苹果       价格为:15
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
请选择:
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出
请选择:4
所购商品清单:
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
请选择:
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出
请选择:3
--银行卡账号登陆--
请输入账号:123
请输入密码:123
欢迎登陆
应付款:[75]
请输入被转款人的账号:123456
请输入转账金额:75
成功向账户[123456]转账[75]元!
付款成功
编号   名称   价格
-------------------
1      榴莲    60
2      苹果    15
请选择:
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出
请选择:5
欢迎下次光临

Process finished with exit code 0
6)、日志查看
F:\PyCharm\script\atm_shopping\bank\log\atm_log.txt

2018-05-03 16:52:51  user: root  process_id:14244 modual:logger.py line:19 level:INFO message:开户成功:姓名[映山红],账号[123456],额度[10000]
2018-05-03 16:54:11  user: root  process_id:13460 modual:logger.py line:19 level:INFO message:银行卡账户[123456] 登陆成功
2018-05-03 16:54:19  user: root  process_id:13460 modual:logger.py line:19 level:INFO message:用户[123456]  查询
2018-05-03 17:01:59  user: root  process_id:6444 modual:logger.py line:19 level:INFO message:银行卡账户[123] 登陆成功
2018-05-03 17:02:11  user: root  process_id:6444 modual:logger.py line:19 level:INFO message:账户[123]  转账给账户[123456] [75]元
2018-05-03 17:02:11  user: root  process_id:6444 modual:logger.py line:19 level:INFO message:账户[123456]  收到账户[123]转账 [75]元
2018-05-03 17:02:15  user: root  process_id:6444 modual:logger.py line:19 level:INFO message:账户[123] 退出成功

F:\PyCharm\script\atm_shopping\shopping\log\shopping_log.txt
用户:12345   商品:榴莲    价格:60    时间:2018-05-03 17:02:11
用户:12345   商品:苹果    价格:15    时间:2018-05-03 17:02:11

二、程序事例(安照readme中的目录结构顺序)

(一)、ATM程序

1)atm.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
import os ,sys
basedir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取bank目录在绝对路径
sys.path.append(basedir)
from user_login import login
from  func import function
print(‘---登陆认证---‘)
account=login.logion()#登陆认证
info=‘‘‘
1:查询         2:提现
3:转账         4:还款
5:改密         6:退出
‘‘‘
select={
    ‘1‘:function.querry_moeny,
    ‘2‘:function.withdrawal,
    ‘3‘:function.transfer_accounts,
    ‘4‘:function.repayment,
    ‘5‘:function.change_password,
    ‘6‘:function.logout
}
if account:#登陆成功后方可执行查询等等。。。
    while True:
        print(info)
        user_select=input(‘请选择:‘).strip()
        if select.get(user_select):#判断用户输入是否在字典select中
            select[user_select](account)#执行对应的函数
        else:
            print(‘\033[32;1m请输入正确选项!\033[0m‘)

2)、atm_bank.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
from __future__ import unicode_literals
import os,sys,pickle,shelve
basdir=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(basdir)
from func import logger
filedir=os.path.join(basdir,‘user_data‘)
time=3#密码可以输错3次
def open_account():#
        try:
            ‘‘‘开户,将用户的全部信息记录到目录user_data中以账号命名的后缀为pkg的文件中‘‘‘
            print(‘----开始开户,请按提示输入---‘)
            account=input(‘请输入账号:‘).strip()
            f_user_account = os.path.join(filedir, ‘%s.pkl‘%account)
            while os.path.exists(f_user_account):#判断账户是否存在
                    print(‘账户已存在,请重新输入...‘)
                    account = input(‘请输入账号:‘).strip()
                    f_user_account = os.path.join(filedir, ‘%s.pkl‘ % account)#获取账户所在文件的绝对路径
            name=input(‘请输入姓名:‘).strip()
            idenfied=input(‘请输入身份证号:‘).strip()
            money=int(input(‘请输入额度:‘).strip())
            status=input(‘请输入账户状态,默认为unlock,(Enter):‘).strip()
            while status !=‘‘ and status != ‘lock‘:
                print(‘请输入unlock|lock,或者press Enter‘)
                status = input(‘请输入账户状态,默认为unlock,(Enter):‘).strip()
            if status ==‘‘:
                status=‘unlock‘#账号默认状态
            password=input(‘请输入密码:‘).strip()
            account_info={‘account‘:account,‘password‘:password,‘time‘:time,‘money‘:money,‘name‘:name,‘identified‘:idenfied,‘status‘:status,‘edu‘:money}
            filename=os.path.join(filedir,‘%s.pkl‘%account)
            f_account_info=open(filename,‘wb‘)#用pickle存储用户详细信息
            pickle.dump(account_info,f_account_info)
            f_account_info.close()
            print(‘开户成功:姓名[%s],账号[%s],额度[%s]‘%(account_info[‘name‘],account_info[‘account‘],account_info[‘money‘]))
            logger.logger(‘开户成功:姓名[%s],账号[%s],额度[%s]‘%(account_info[‘name‘],account_info[‘account‘],account_info[‘money‘]))
            ‘‘‘将用户的账号信息记录到目录user_data中user_account文件中‘‘‘
            ‘‘‘
            f_user_account=os.path.join(filedir,‘user_account‘)#用shelve存储用户账号信息
            f_user_account=shelve.open(f_user_account)
            f_user_account[account]=account
            f_user_account.close()
            ‘‘‘
        except Exception as e:
            print(‘系统异常:%s‘%e)
            logger.logger(‘开户失败,%s‘%e)

def  set_lock():
        try:
                while True:
                        account=input(‘请输入要解锁或者冻结账户的账号(3退出):‘).strip()
                        if account == ‘3‘:break
                        f_user_account = os.path.join(filedir, ‘%s.pkl‘ % account)
                        if os.path.exists(f_user_account) and  os.path.getsize(f_user_account)>0:#如果文件存在并且不为空
                                ‘‘‘取出用户账户信息‘‘‘
                                f=open(r‘%s‘%f_user_account,‘rb‘)
                                account_info=pickle.load(f)
                                f.close()
                                ‘‘‘验证身份‘‘‘
                                identified = input(‘请输入你的身份证号码:‘).strip()
                                while identified !=  account_info[‘identified‘]:
                                        print(‘身份证输入错误,请重新输入!‘)
                                        identified = input(‘请输入你的身份证号码:‘).strip()
                                else:
                                        ‘‘‘解锁‘‘‘
                                        print(‘用户状态:%s‘%account_info[‘status‘])#查看账户当前状态
                                        lock_status=input(‘请输入1或者2或者3(1:解锁,2:冻结,3:退出):‘)
                                        if lock_status == ‘3‘:break
                                        while lock_status != ‘1‘ and lock_status !=‘2‘:
                                                print(‘输入错误,请重新输入!‘)
                                                lock_status = input(‘请输入1或者2或者3(1:解锁,2:冻结,3:退出):‘)
                                                if lock_status == ‘3‘: break
                                        else:
                                                if lock_status == ‘1‘:
                                                        lock_status=‘unlock‘
                                                else:
                                                        lock_status = ‘lock‘
                                                f = open(r‘%s‘ % f_user_account, ‘wb‘)
                                                account_info[‘status‘] = lock_status
                                                account_info[‘time‘]=3
                                                pickle.dump(account_info,f)
                                                f.close()
                                                print(‘操作成功,账户当前状态为:%s‘%account_info[‘status‘])
                                                logger.logger(‘设置锁状态操作成功,账户当前状态为:%s‘%account_info[‘status‘])
                        else:print(‘账户不存在,或者账户信息为空‘)
        except Exception as e:
                print(‘系统异常:%s‘ % e)
                logger.logger(‘系统异常:%s‘ % e)

def reset_password():
    ‘‘‘根据账户和身份证号码重新设置密码‘‘‘
    pass
def querry_account_info_all():
    ‘‘‘查询所有账户信息‘‘‘
    pass
if __name__==‘__main__‘:
    ‘‘‘ATM管理员
    open_account():开户
    set_lock():设置账户状态
    ‘‘‘
    func={
        ‘1‘:open_account,
        ‘2‘:set_lock,
        ‘3‘: sys.exit
    }
    while True:
        print(‘‘‘
        1:开户
        2:解锁或者冻结账户
        3:退出
        ‘‘‘)
        active=input(‘请选择:‘)
        #if active == ‘3‘: break
        if  active in  func.keys():
            func[active]()
        else:print(‘输入错误,请重新输入!‘)

3)、function.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
import os,sys,pickle
bank_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(bank_dir)
from bank.func import logger
from bank.func import logger
#logger.logger(‘test‘)
user_data_dir=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),‘user_data‘)#获取账户信息所在的目录
def get_account_info(account):
    ‘‘‘获取用户信息‘‘‘
    account_file = os.path.join(user_data_dir, ‘%s.pkl‘ % account)
    if not os.path.exists(account_file):
        return False
    else:
        f = open(account_file, ‘rb‘)
        account_info = pickle.load(f)
        f.close()
        return account_info
def write_account_info(account,account_info):
    ‘‘‘保存用户信息‘‘‘
    account_file = os.path.join(user_data_dir, ‘%s.pkl‘ % account)
    f = open(account_file, ‘wb‘)
    pickle.dump(account_info,f)
    f.close()
    #print(‘操作成功‘)


def querry_moeny(account):#查询额度,account为查询人的账号
    account_info=get_account_info(account)
    print(‘\033[96;1m信用额度为:%s,可用额度为:%s 元\033[0m‘%(account_info[‘edu‘],account_info[‘money‘]))
    #logger.logging.info(‘用户[%s]  查询‘%account)
    logger.logger(‘用户[%s]  查询‘%account)
def transfer_accounts(account_from):#转账
    ‘‘‘account_from:转款人账号
       account_to:被转款人账号
       money:转款金额
    ‘‘‘
    account_to=input(‘请输入被转款人的账号:‘)
    account_info_from=get_account_info(account_from)
    account_info_to = get_account_info(account_to)
    if account_info_to:
        while True:
            try:
                money=int(input(‘请输入转账金额:‘).strip())
                break
            except Exception:
                print(‘\033[101;1m请输入数字金额!\033[0m‘)
        if money <= account_info_from[‘money‘]:
            account_info_from[‘money‘]-=money
            account_info_to=get_account_info(account_to)
            account_info_to[‘money‘]+=int(money)
            write_account_info(account_from, account_info_from)
            write_account_info(account_to,account_info_to)
            print(‘\033[91;1m成功向账户[%s]转账[%s]元!\033[0m‘%(account_to,money))
            #logger.logger(‘账户[%s]  转账给账户[%s] [%s]元‘%(account_from,account_to,money))
            #logger.logger(‘账户[%s]  收到账户[%s]转账 [%s]元‘%(account_to,account_from,money))
            logger.logger(‘账户[%s]  转账给账户[%s] [%s]元‘%(account_from,account_to,money))
            logger.logger(‘账户[%s]  收到账户[%s]转账 [%s]元‘%(account_to,account_from,money))
            return True
        else:
            print(‘\033[103;1m可用额度不足!\033[0m‘)
            logger.logger(‘账户[%s]  转账给账户[%s] [%s]元 失败 因可用额度不足‘ % (account_from, account_to, money),‘critical‘)
            return False
    else:
        print(‘\033[103;1m账户不存在!\033[0m‘)
        logger.logger(‘账户[%s]  转账给账户[%s] 失败 因账户不存在‘ % (account_from, account_to))
        return None

def withdrawal(account):
    ‘‘‘取款‘‘‘
    money=int(input(‘请输入取款金额:‘))
    account_info=get_account_info(account)
    if money<=account_info[‘money‘]:
        account_info[‘money‘]-=money
        write_account_info(account,account_info)
        print(‘\033[91;1m成功取款[%s]元\033[0m‘%money)
        logger.logger(‘账户[%s]  取款[%s] 元‘ % (account,money))
    else:
        print(‘可用额度不足‘)
        logger.logger(‘账户[%s]  取款[%s] 元 失败 因可用额度不足‘ % (account, money))
def repayment(account):
    ‘‘‘还款‘‘‘
    money=int(input(‘请输入还款金额:‘))
    account_info=get_account_info(account)
    account_info[‘money‘] += money
    write_account_info(account,account_info)
    print(‘\033[91;1m成功还款[%s]元\033[0m‘%money)
    logger.logger(‘账户[%s]  还款[%s] 元‘ % (account, money))
def change_password(account):
    ‘‘‘修改密码‘‘‘
    account_info=get_account_info(account)
    old_pw=input(‘请输入旧密码:‘).strip()
    while old_pw !=account_info[‘password‘]:
        print(‘旧密码输入错误,请重新输入‘)
        old_pw = input(‘请输入旧密码:‘).strip()
    new_pw1=input(‘请输入新密码:‘)
    new_pw2=input(‘请再次输入新密码:‘)
    while new_pw1 != new_pw2:
        print(‘密码不一致,请重新输入:‘)
        new_pw1 = input(‘请输入新密码:‘)
        new_pw2 = input(‘请再次输入新密码:‘)
    else:
        account_info[‘password‘]=new_pw1
        write_account_info(account,account_info)
        print(‘\033[91;1m修改密码成功\033[0m‘)
        logger.logger(‘账户[%s]  修改密码成功‘ %account)
def logout(account):
    logger.logger(‘账户[%s] 退出成功‘ % account)
    sys.exit()

4)、logger.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
import os,sys
#log_file=os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),‘log‘),‘atm_log.txt‘)
def logger(msg,*agrv,**kargv):
    import logging
    log_file = os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ‘log‘), ‘atm_log.txt‘)
    logging.basicConfig(format=‘%(asctime)s  user: %(name)s  process_id:%(process)d modual:%(filename)s line:%(lineno)d level:%(levelname)s message:%(message)s‘,datefmt=‘%Y-%m-%d %H:%M:%S‘,filename=log_file,level=logging.DEBUG)
    if len(agrv)>0:
        if agrv[0] == ‘warning‘:
            logging.warning(msg)
        if agrv[0] == ‘critical‘:
            logging.critical(msg)
    else:
            logging.info(msg)

5)、login.py#bank

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#功能:用户登陆,密码失败3次,账户将被锁住
#created by xkq
#date: 201803
import pickle,sys,getpass,os
basdir=os.path.dirname(os.path.abspath(__file__))#获取当前文件所在的目录
sys.path.append(basdir)
user_data_dir=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),‘user_data‘)#用户账号信息所在的目录
bank_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(bank_dir)
from bank.func import logger
def account_get(func):
    ‘‘‘获取用户账号信息‘‘‘
    def wrap():
        global f_user_account,account_info
        account=input(‘请输入账号:‘).strip()
        f_user_account = os.path.join(user_data_dir, ‘%s.pkl‘%account)#获取用户账号信息所在文件的绝对路径
        while not  os.path.exists(f_user_account):#判断账户是否存在
                print(‘账户不存在,请重新输入...‘)
                account = input(‘请输入账号:‘).strip()
                f_user_account = os.path.join(user_data_dir, ‘%s.pkl‘ % account)
                if account== "exit":
                    sys.exit()
        else:
            f=open(f_user_account,‘rb‘)
            account_info=pickle.load(f)
            print(account_info)
            f.close()
        return (func())
    return wrap

def write_user():#保存用户账号信息
    #print(account_info)
    f = open(f_user_account, ‘wb‘)
    pickle.dump(account_info, f)
    f.close()

@account_get
def logion():
    ‘‘‘密码验证‘‘‘
    FLAG=False
    #print(account_info)
    if account_info[‘status‘] ==‘unlock‘:#判断账户是否被锁
            password = input(‘请输入密码:‘)
            #password = getpass.getpass(‘请输入密码:‘)

            while password != account_info[‘password‘]:
                #print(type(account_info[user][‘pw‘]))
                account_info[‘time‘] -=1#每输错一次密码,机会就会减少一次
                if account_info[‘time‘] == 0:
                    account_info[‘status‘] = ‘lock‘
                    print(‘\033[31;1m密码连续输入不正确,账号%s已被锁,请联系400-123456进行解锁。\033[0m‘ % account_info[‘account‘])
                    write_user()
                    #logger.logging.info(‘账户[%s] 被锁 因密码连续3次输入不正确‘ % account_info[‘account‘])
                    logger.logger(‘账户[%s] 被锁 因密码连续3次输入不正确‘ % account_info[‘account‘],‘critical‘)
                    sys.exit()
                #print(account_info[user][‘time‘])
                print(‘密码不正确,你还有%s次机会会,请重新输入:‘%account_info[‘time‘])
                #logger.logging.info(‘账户[%s] 登陆失败 因密码输入错误‘ % account_info[‘account‘])
                logger.logger(‘账户[%s] 登陆失败 因密码输入错误‘ % account_info[‘account‘],‘warning‘)
                # password = getpass.getpass(‘请输入密码:‘)
                password = input(‘请输入密码:‘)
                if password == ‘exit‘:
                    write_user()
                    sys.exit()
            else:
                account_info[‘time‘]=3
                print(‘\033[36;1m欢迎登陆\033[0m‘)
                #logger.logging.info(‘银行卡账户[%s] 登陆成功‘%account_info[‘account‘])
                logger.logger(‘银行卡账户[%s] 登陆成功‘%account_info[‘account‘])
                write_user()
                FLAG = True

    else:
        print(‘\033[31;1m账号%s已被锁,请联系400-123456进行解锁.\033[0m‘%account_info[‘account‘])
        #logger.logging.info(‘账户[%s] 登陆失败 未被解锁‘ % account_info[‘account‘])
        logger.logger(‘账户[%s] 登陆失败 未被解锁‘ % account_info[‘account‘],‘warning‘)
        sys.exit()
    #return FLAG
    return account_info[‘account‘]#返回登录账号
if __name__ == ‘__main__‘:
    logion()

(二)、shopping程序

1)、goods_put_or_off.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
import  pickle,sys,os
base_dir_shopping=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir_shopping)
goods_file=os.path.join(os.path.join(base_dir_shopping,‘goods‘),‘goods.pkl‘)
def put_on_shelves(goods_file):#商品上架
    print(‘--商品上架--‘)
    if os.path.exists(goods_file) and os.path.getsize(goods_file)>0:
        f=open(goods_file,‘rb‘)
        goods=pickle.load(f)
        f.close()
        i = len(goods) + 1
        while True:
            thing = input(‘请输入商品名称(退出:exit):‘)
            if thing == ‘exit‘: break
            price = input(‘请输入商品价格:‘)
            goods[‘%s‘ % i] = [thing, price]
            i += 1
        f = open(goods_file, ‘wb‘)
        goods = pickle.dump(goods, f)
        f.close()
    else:
        goods = {}
        i = 1
        while True:
            thing = input(‘请输入商品名称(退出:exit):‘)
            if thing == ‘exit‘: break
            price = input(‘请输入商品价格:‘)
            goods[‘%s‘ % i] = [thing, price]
            i += 1
        f = open(goods_file, ‘wb‘)
        goods = pickle.dump(goods, f)
        f.close()

def show_goods():#展示已上架商品
    if os.path.exists(goods_file) and os.path.getsize(goods_file) > 0:
        f = open(goods_file, ‘rb‘)
        goods = pickle.load(f)
        f.close()
        print(‘‘‘\033[36;1m编号   名称   价格\033[0m\n-------------------‘‘‘)
        for k, v in goods.items():
            print(‘‘‘%s       %s     %s‘‘‘ % (k, v[0], v[1]))
def pull_off_shelves():#商品下架
    pass
if __name__==‘__main__‘:
    show_goods()
    put_on_shelves(goods_file)

2)、shopping

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#created by xkq
#date: 2018
import sys,os,pickle
base_dir_shopping=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir_shopping)
from user_login.login import *
from func.function import  *
goods_file=os.path.join(os.path.join(base_dir_shopping,‘goods‘),‘goods.pkl‘)
#goods={‘1‘:[‘苹果‘,20],‘2‘:[‘香蕉‘,15],‘3‘:[‘毛巾‘,12.3],‘4‘:[‘牙刷‘,7],‘5‘:[‘牙膏‘,21],\ ‘6‘:[‘大米‘,150],‘7‘:[‘手机‘,2000]}
user=logion()#购物登陆认证
f = open(goods_file, ‘rb‘)
goods = pickle.load(f)
f.close()
buy_goods = []
while user:
    show_goods(goods)
    print(‘‘‘\033[31;1m请选择:\033[0m
    1:购物
    2:退商品
    3:付款
    4:购物清单
    5:退出‘‘‘)
    select=int(input(‘\033[31;1m请选择:\033[0m‘))
    if select==1:
        shopping(goods, buy_goods,user)
    if select == 2:
        returned_purchase(buy_goods)
    if select==3:
        pay( buy_goods, user)
    if select==4:
        show_buy_goods(buy_goods)
    if select==5:
        print(‘欢迎下次光临‘)
        logout_shoping()

3)、user_set.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#function:
#created by xkq
#date: 2018
import os,sys
base_dir_shopping=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir_shopping)
from user_login.user_create import *
if __name__==‘__main__‘:
    main()

4)、function.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#created by xkq
#date: 2018
import datetime,os,sys

bank_dir_login=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(bank_dir_login)
from bank.user_login import login
from bank.func.function import transfer_accounts,logout
#import logging
#from bank.func import logger


#购物日志文件路径
shopping_log_file=os.path.join(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),‘log‘),‘shopping_log.txt‘)
#shopping_log=‘F:\PyCharm\script\day520180412\atm_shopping\shopping\log\shopping_log.txt‘

def logger(user,shangpin,price):#购物日志记录函数
    time = datetime.datetime.now().strftime(‘%F %T‘)
    f=open(shopping_log_file,‘a‘)
    f.write(‘用户:%s   商品:%s    价格:%s    时间:%s\n‘%(user,shangpin,price,time))
    f.flush()
    f.close()

def show_goods(goods):#展示商品
    print(‘‘‘\033[36;1m编号   名称   价格\033[0m\n-------------------‘‘‘)
    for k,v in goods.items():
        print(‘‘‘%s      %s    %s‘‘‘%(k,v[0],v[1]))
def shopping(goods,buy_thing,user):#购物
    thing=input(‘\033[31;1m请选择要购买的商品编号:\033[0m‘)
    buy_thing.append([user,goods[thing][0],goods[thing][1]])
    print(‘你选择的了:%s       价格为:%s‘%(goods[thing][0],goods[thing][1]))
def  returned_purchase(buy_thing):#退货
    tmp={}
    for i,k in enumerate(buy_thing,1):
        print(i,k[1])
        tmp[i]=k
    num = int(input(‘\033[32;1m请选择一个要退的商品编号:\033[0m‘))
    buy_thing.remove(tmp[num])
    print(‘你退的是:%s       价格为:%s‘%(tmp[num][1],tmp[num][2]))

login_FALG=True
account=None
def pay(buy_thing,user):
    ‘‘‘
    付款
    login_FALG=True#记录登陆标志,True表示没有登陆,False表示已登录,避免每次付款都要重新登陆认证
    account=None#记录用户登陆的银行卡账号
    ‘‘‘
    global login_FALG,account
    pay_money=0
    for i in buy_thing:
        #print(i[2])
        pay_money+=int(i[2])
    #has_money=user_all[user][‘money‘]
    print(‘--银行卡账号登陆--‘)
    if login_FALG:
        account=login.logion()#银行卡登陆认证
        login_FALG=False
    print(‘应付款:[%s]‘%pay_money)
    if account:
        res=transfer_accounts(account)
        if res==None:
            print(‘\033[31;1m请重新选择付款并输入正确账号!\033[0m‘)
        elif res:
            print(‘\033[36;1m付款成功\033[0m‘)
            for i in buy_thing:
                logger(i[0], i[1], i[2])
        else:
            print(‘\033[41;1m钱不够,请推掉部分商品!\033[0m‘)
def show_buy_goods(buy_thing):
    print(‘\033[46;1m所购商品清单:\033[0m‘)
    print(‘‘‘编号   名称   价格\n-------------------‘‘‘)
    for i,k in enumerate(buy_thing,1):
        print(‘‘‘%s      %s    %s‘‘‘ %(i,k[1],k[2]))
def logout_shoping():
    if login_FALG==False:
        logout(account)
    else:
        sys.exit()

if __name__==‘__main__‘:
    pass

5)、login.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#功能:用户登陆,密码失败3次,账户将被锁住
#created by xkq
#date: 201803
import pickle,sys,getpass,os,shelve
file=os.path.join(os.path.dirname(os.path.abspath(__file__)),‘user_info_all‘)
f=shelve.open(file)
def logion():
    FLAG=False
    user=input(‘请输入用户名:‘)
    while user not in f.keys():
        print(‘用户名不存在,请重新输入‘)
        user = input(‘请输入用户名:‘)
        if user == "exit":
            sys.exit()
    else:
        user_info=f.get(user)
        if user_info[‘status‘] == ‘unlock‘:
                password = input(‘请输入密码:‘)
                #password = getpass.getpass(‘请输入密码:‘)
                while password != user_info[‘pw‘]:
                    user_info[‘time‘]-=1
                    if user_info[‘time‘]== 0:
                        user_info[‘status‘] = ‘lock‘
                        print(‘密码连续输入不正确,用户%s已被锁,请联系400-123456进行解锁。‘ % user)
                        #write_user()
                        f[user]=user_info
                        f.close()
                        sys.exit()
                    print(‘密码不正确,你还有%s次机会会,请重新输入:‘%user_info[‘time‘])
                    # password = getpass.getpass(‘请输入密码:‘)
                    password = input(‘请输入密码:‘)
                    if password == ‘exit‘:
                        f[user] = user_info
                        f.close()
                        sys.exit()
                else:
                    user_info[‘time‘]=3
                    f[user] = user_info
                    print(‘\033[36;1m欢迎登陆\033[0m‘)
                    #write_user()
                    f.close()
                    FLAG = True

        else:
            print(‘\033[31;1m用户%s已被锁,请联系400-123456进行解锁.\033[0m‘%user)
            sys.exit()
    #return FLAG
    return user
if __name__ == ‘__main__‘:
    logion()

6)、user_create.py

#!/usr/bin/env python
#_*_ coding:utf-8 _*_  
#encoding=utf-8
#给购物客户创建用户、重置密码、重置锁状态、查看用户账户信息等
#created by xkq
#date: 2018
import os,sys,shelve
basdir=os.path.dirname((os.path.abspath(__file__)))
user_info_all_file=os.path.join(basdir,‘user_info_all‘)#存放用户信息

time=3#密码可以输错3次
def create_user():#创建用户
    f = shelve.open(user_info_all_file)
    while True:
        try:
            name=input(‘请输入用户名(exit:退出):‘)
            if name == ‘exit‘:break
            if name not in f.keys():
                password=input(‘请输入密码:‘)
                f[name]={‘pw‘:password,‘time‘:time,‘status‘:‘unlock‘}
                f.close()
            else:
                print(‘用户已存在‘)
                f.close()
        except Exception as e:
                print(‘系统异常:%s‘%e)
                f.close()
def dell_user():#创删除用户
    f = shelve.open(user_info_all_file)
    while True:
        try:
            name=input(‘请输入用户名(exit:退出):‘)
            if name == ‘exit‘:break
            if name  in f.keys():
                del f[name]
                f.close()
                print(‘\033[36;1m删除成功!\033[0m‘)
            else:
                print(‘用户不存在‘)
                f.close()
        except Exception as e:
                print(‘系统异常:%s‘%e)
                f.close()

def reset_password():#重置密码
    while True:
        f = shelve.open(user_info_all_file)
        name=input(‘请输入重置密码的用户名(exit"退出):‘)
        if name==‘exit‘:break
        password=input(‘请输入密码:‘)
        user_info=f.get(name)
        user_info[‘pw‘]=password
        f[name]=user_info
        f.close()
        print(‘\033[36;1m重置密码成功!\033[0m‘)
def reset_lock():#重置锁状态
    while True:
        f = shelve.open(user_info_all_file)
        name=input(‘请输入重置锁状态的用户名(exit"退出):‘).strip()
        if name==‘exit‘:
            f.close()
            break
        user_info=f.get(name)
        lock_status = input(‘请输入1或者2(1:解锁,2:枷锁):‘)
        while lock_status !=‘1‘ and  lock_status != ‘2‘:
            print(‘\033[31;1m输入错误,请重新输入!\033[0m‘)
            lock_status = input(‘请输入1或者2(1:解锁,2:枷锁):‘)
        else:
            if lock_status==‘1‘:
                user_info[‘status‘]=‘unlock‘
            else:
                user_info[‘status‘] = ‘lock‘
            f[name]=user_info
            f.close()
            print(‘\033[36;1m重置成功,锁状态为[%s]!\033[0m‘%user_info[‘status‘])


def show_user_all():#查看用户账户信息
    f = shelve.open(user_info_all_file)
    print(‘用户   可重试次数   锁状态‘)
    for i in f.keys():
        print(‘%s        %s         %s‘%(i,f.get(i)[‘time‘],f.get(i)[‘status‘]))
    f.close()
def main():
    info = ‘‘‘
        1:创建用户
        2:删除用户
        3:重置密码
        4:重置锁状态
        5:查看用户信息
        6:退出
        ‘‘‘
    user_info = {
        ‘1‘: create_user,
        ‘2‘:dell_user,
        ‘3‘: reset_password,
        ‘4‘: reset_lock,
        ‘5‘: show_user_all,
        ‘6‘: sys.exit
    }
    while True:
        print(info)
        select = input(‘请选择:‘)
        if select in user_info.keys():
            user_info[select]()
        else:
            print(‘\033[31;1m输入错误,请重新输入!\033[0m‘)
if __name__==‘__main__‘:
    main()

  

 

以上是关于python3-模拟ATM_shopping的主要内容,如果未能解决你的问题,请参考以下文章

如何升级到python3版本并且安装pip3及ipython3

Android 逆向修改运行中的 Android 进程的内存数据 ( 运行环境搭建 Android 模拟器安装 | 拷贝 Android 平台可执行文件和动态库到 /data/system )(代码片

编写三各类TicketSaleWindowTicketSaleCenter分别代表票信息售票窗口售票中心。 售票中心分配一定数量的票,由若干个售票窗口进行出售,利用你所学的线程知识来模拟此售票(代码片

时间片轮转算法和优先级调度算法模拟实现

[Python3 练习] 005 汉诺塔1

操作系统实验二(调度算法模拟-先进先出-时间片轮转法-优先服务调度算法)