书上一道题需要实现功能"根据账号查询密码, 复制密码到剪贴板". 账号和密码储存在代码字典中.
问题描述:
作为Python新手从代码(如下)看只知道:
1. sys.argv初始包含一行文件路径.
2. 需要将待查询的账号传入sys.argv.
怎么操作呢?
#! python3 #pw.py - An inssecure password locker program. #Run this program in CMD, parameter (account) load after filename. Like: pw.py email PASSWORDS={‘email‘:‘F7minlBDDuvJJux‘, ‘blog‘:‘VmALvWyKAxiVH5‘,‘luggage‘:‘12345‘} import sys,pyperclip if len(sys.argv)<2: print(‘Usage: python pw.py [account] - copy account password‘) sys.exit() account=sys.argv[1] # first command line arg is the account name if account in PASSWORDS: pyperclip.copy(PASSWORDS[account]) print(‘Password for ‘+account+‘ copied to clipboard.‘) else: print(‘There is no account named ‘+account)
解决思路:
命令行参数, 通过命令行来操作了.
在CMD中cd到pw.py的目录下, 敲如命令时将参数置于文件名之后. 如下图, 搞定了.
D:\DIV\PyScripts>pw.py blog Password for blog copied to clipboard. D:\DIV\PyScripts>pw.py luggage Password for luggage copied to clipboard. D:\DIV\PyScripts>pw.py email Password for email copied to clipboard. D:\DIV\PyScripts>
备注:
sys.argv用import导入, 初始值是运行文件所在路径+文件名, 传入账号之后账号的值被添加到了sys.argv中, 如下:
[‘D:\\DIV\\PyScripts\\pw.py‘, ‘email‘]
程序运行完成之后再试图打印sys.argv就不行了, 传入的参数被释放.
以上是Python新手对于sys.argv的一点粗浅认识, 如果有没理解对的地方, 欢迎各位指正.