将《Automate the Boring Stuff with Python》的语法部分学完了,开始依葫芦画瓢做第一个项目。

#! python3
# pw.py - An insecure password locker program.PASSWORD = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6','blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt','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 namerif account in PASSWORD:pyperclip.copy (PASSWORD[account])print('Password for ' + account + ' coopied to clipboard.')
else:print('There is no account named ' + account)

以上是code,但是运行时提示No module named pyperclip,于是上网找资料说要安装模块,尝试:(我这才发现原来pip install也可用于windows,只要装了python即可)

C:\Users\simmy>pip install pyperclip
Collecting pyperclip
  Downloading pyperclip-1.5.27.zip
Installing collected packages: pyperclip
  Running setup.py install for pyperclip
Successfully installed pyperclip-1.5.27
You are using pip version 7.1.2, however version 8.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

C:\Users\simmy>pip freeze
pyperclip==1.5.27
You are using pip version 7.1.2, however version 8.1.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' comm
and.

完后依然提示错误,于是在Python IDLE上测试:

>>> import pyperclip
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import pyperclip

ImportError: No module named 'pyperclip'

同样报错,后来查询后,发现作者是自己写的模块,在这里提到:https://inventwithpython.com/hacking/chapter2.html: Downloading pyperclip.py
Almost every program in this book uses a custom module I wrote called pyperclip.py. This module provides functions for letting your program copy and paste text to the clipboard. This module does not come with Python, but you can download it from: http://invpy.com/pyperclip.py

This file must be in the same folder as the Python program files that you type. (A folder is also called a directory.) Otherwise you will see this error message when you try to run your program:

ImportError: No module named pyperclip

从这下载:https://inventwithpython.com/pyperclip.py

然后放入:C:\Users\xxx\AppData\Local\Programs\Python\Python35

问题解决。

pyperclip.py code如下:

--------------------------------------------------------------------------------------

"""
PyperclipA cross-platform clipboard module for Python. (only handles plain text for now)
By Al Sweigart al@inventwithpython.com
BSD LicenseUsage:import pyperclippyperclip.copy('The text to be copied to the clipboard.')spam = pyperclip.paste()On Windows, no additional modules are needed.
On Mac, this module makes use of the pbcopy and pbpaste commands, which should come with the os.
On Linux, this module makes use of the xclip or xsel commands, which should come with the os. Otherwise run "sudo apt-get install xclip" or "sudo apt-get install xsel"Otherwise on Linux, you will need the gtk or PyQt4 modules installed.The gtk module is not available for Python 3, and this module does not work with PyGObject yet.
"""__version__ = '1.5.6'import platform, os
from subprocess import call, Popen, PIPEdef _pasteWindows():CF_UNICODETEXT = 13d = ctypes.windlld.user32.OpenClipboard(None)handle = d.user32.GetClipboardData(CF_UNICODETEXT)data = ctypes.c_wchar_p(handle).valued.user32.CloseClipboard()return datadef _copyWindows(text):GMEM_DDESHARE = 0x2000CF_UNICODETEXT = 13d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)try:  # Python 2if not isinstance(text, unicode):text = text.decode('mbcs')except NameError:if not isinstance(text, str):text = text.decode('mbcs')d.user32.OpenClipboard(None)d.user32.EmptyClipboard()hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)pchData = d.kernel32.GlobalLock(hCd)ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)d.kernel32.GlobalUnlock(hCd)d.user32.SetClipboardData(CF_UNICODETEXT, hCd)d.user32.CloseClipboard()def _pasteCygwin():CF_UNICODETEXT = 13d = ctypes.cdlld.user32.OpenClipboard(None)handle = d.user32.GetClipboardData(CF_UNICODETEXT)data = ctypes.c_wchar_p(handle).valued.user32.CloseClipboard()return datadef _copyCygwin(text):GMEM_DDESHARE = 0x2000CF_UNICODETEXT = 13d = ctypes.cdlltry:  # Python 2if not isinstance(text, unicode):text = text.decode('mbcs')except NameError:if not isinstance(text, str):text = text.decode('mbcs')d.user32.OpenClipboard(None)d.user32.EmptyClipboard()hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)pchData = d.kernel32.GlobalLock(hCd)ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)d.kernel32.GlobalUnlock(hCd)d.user32.SetClipboardData(CF_UNICODETEXT, hCd)d.user32.CloseClipboard()def _copyOSX(text):text = str(text)p = Popen(['pbcopy', 'w'], stdin=PIPE)try:# works on Python 3 (bytes() requires an encoding)p.communicate(input=bytes(text, 'utf-8'))except TypeError:# works on Python 2 (bytes() only takes one argument)p.communicate(input=bytes(text))def _pasteOSX():p = Popen(['pbpaste', 'r'], stdout=PIPE)stdout, stderr = p.communicate()return bytes.decode(stdout)def _pasteGtk():return gtk.Clipboard().wait_for_text()def _copyGtk(text):global cbtext = str(text)cb = gtk.Clipboard()cb.set_text(text)cb.store()def _pasteQt():return str(cb.text())def _copyQt(text):text = str(text)cb.setText(text)def _copyXclip(text):p = Popen(['xclip', '-selection', 'c'], stdin=PIPE)try:# works on Python 3 (bytes() requires an encoding)p.communicate(input=bytes(text, 'utf-8'))except TypeError:# works on Python 2 (bytes() only takes one argument)p.communicate(input=bytes(text))def _pasteXclip():p = Popen(['xclip', '-selection', 'c', '-o'], stdout=PIPE)stdout, stderr = p.communicate()return bytes.decode(stdout)def _copyXsel(text):p = Popen(['xsel', '-i'], stdin=PIPE)try:# works on Python 3 (bytes() requires an encoding)p.communicate(input=bytes(text, 'utf-8'))except TypeError:# works on Python 2 (bytes() only takes one argument)p.communicate(input=bytes(text))def _pasteXsel():p = Popen(['xsel', '-o'], stdout=PIPE)stdout, stderr = p.communicate()return bytes.decode(stdout)# Determine the OS/platform and set the copy() and paste() functions accordingly.
if 'cygwin' in platform.system().lower():_functions = 'Cygwin' # for debuggingimport ctypespaste = _pasteCygwincopy = _copyCygwin
elif os.name == 'nt' or platform.system() == 'Windows':_functions = 'Windows' # for debuggingimport ctypespaste = _pasteWindowscopy = _copyWindows
elif os.name == 'mac' or platform.system() == 'Darwin':_functions = 'OS X pbcopy/pbpaste' # for debuggingpaste = _pasteOSXcopy = _copyOSX
elif os.name == 'posix' or platform.system() == 'Linux':# Determine which command/module is installed, if any.xclipExists = call(['which', 'xclip'],stdout=PIPE, stderr=PIPE) == 0xselExists = call(['which', 'xsel'],stdout=PIPE, stderr=PIPE) == 0gtkInstalled = Falsetry:# Check it gtk is installed.import gtkgtkInstalled = Trueexcept ImportError:passif not gtkInstalled:# Check if PyQt4 is installed.PyQt4Installed = Falsetry:import PyQt4.QtCoreimport PyQt4.QtGuiPyQt4Installed = Trueexcept ImportError:pass# Set one of the copy & paste functions.if xclipExists:_functions = 'xclip command' # for debuggingpaste = _pasteXclipcopy = _copyXclipelif gtkInstalled:_functions = 'gtk module' # for debuggingpaste = _pasteGtkcopy = _copyGtkelif PyQt4Installed:_functions = 'PyQt4 module' # for debuggingapp = PyQt4.QtGui.QApplication([])cb = PyQt4.QtGui.QApplication.clipboard()paste = _pasteQtcopy = _copyQtelif xselExists:# TODO: xsel doesn't seem to work on Raspberry Pi (my test Linux environment). Putting this as the last method tried._functions = 'xsel command' # for debuggingpaste = _pasteXselcopy = _copyXselelse:raise Exception('Pyperclip requires the xclip or xsel application, or the gtk or PyQt4 module.')
else:raise RuntimeError('pyperclip does not support your system.')

转载于:https://blog.51cto.com/helpdesk/1768178

Automate the Boring Stuff with Python学习笔记1相关推荐

  1. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第8章:INPUT VALIDATION

    THE PYINPUTPLUS MODULE PyInputPlus 模块可用以检查输入有效性,避免手工编写代码. 这个手工代码的例子中有一段,except后可不指定exception,表示所有的ex ...

  2. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第10章:ORGANIZING FILES

    SHUTIL 模块 shutil是shell utility的简称,使用此模块需要import shutil. 详见在线文档,在线帮助见help(shutil) >>> shutil ...

  3. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第2章:FLOW CONTROL

    在流程图中,开始和结束圆角矩形表示,菱形表示流控分支,矩形表示实际操作. 布尔值 布尔值包括两个常数,即True和False. 布尔的命名来源于数学家George Boole. 比较操作符 包括==, ...

  4. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第6章:MANIPULATING STRINGS

    操作字符串 字符串可以用单引号或双引号包围,建议用单引号. 如果字符串中含单引号或双引号,可以用\转移(escape).例如\\, \', \", \n等. >>> a=' ...

  5. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第12章:WEB SCRAPING

    Web Scraping是指用程序来下载和处理网络上的内容.Scrap是铲,刮和削的意思. 本章介绍的模块包括webbrowser,requests,bs4和selenium. 项目: 使用WEBBR ...

  6. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第9章:READING AND WRITING FILES

    本章需要用到以下的模块: from pathlib import Path import os 文件和文件路径 文件由文件名和路径组成.Linux以/(forward slash)为根路径,Windo ...

  7. AUTOMATE THE BORING STUFF WITH PYTHON读书笔记 - 第19章:MANIPULATING IMAGES

    本章介绍Pillow模块,可处理图形文件.安装如下: # pillow安装依赖于JPEG源代码 $ sudo yum install libjpeg-turbo-devel $ pip3 instal ...

  8. [python教程入门学习]python学习笔记(CMD执行文件并传入参数)

    本文章向大家介绍python学习笔记(CMD执行文件并传入参数),主要包括python学习笔记(CMD执行文件并传入参数)使用实例.应用技巧.基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋 ...

  9. python学习笔记之编写readConfig读写配置文件

    python学习笔记之编写readConfig读写配置文件_weixin_34055910的博客-CSDN博客

最新文章

  1. CVPR2019论文看点:自学习Anchor原理
  2. PTA基础编程题目集-7-3 逆序的三位数
  3. GPU — CPU-GPU 异构计算系统
  4. 刘宇凡:自媒体不是自媒体 应是志媒体
  5. Improving RGB-D SLAM in dynamic environments: A motion removal approach
  6. allegro标注尺寸设置_标注新升级 | SOLIDWORKS 2020新功能揭秘
  7. 9203 演练 jsp实现增删改查
  8. 听说当今程序员很厉害?不,那是你不了解上古时期的那些神级操作
  9. 如何使用Visual Studio创建SQL Server数据库项目
  10. 官宣:Linux 内核主要贡献者 Linaro「喜提」新任 CEO!
  11. C#不区分大小写的字符串替换(Replace)
  12. 浅析指针(pointer)与引用(reference)
  13. 客户服务器与p2p文件分发,P2P大文件分发技术 | 点量软件
  14. ShuffleNet
  15. 第三章 教育法律法规
  16. (梳理)用Tensorflow实现SE-ResNet(SENet ResNet ResNeXt VGG16)的数据输入,训练,预测的完整代码框架(cifar10准确率90%)
  17. 多媒体的基础知识:感觉媒体、表现媒体、表示媒体、传输媒体、存储媒体
  18. 洪水填充算法_Unity 3D - 洪水填充/油漆桶算法不断崩溃引擎
  19. 周杰伦录音室专辑名字整理,时间倒数
  20. Primo.Ramdisk.Srv.Mui.Setup安装配置教程

热门文章

  1. Eclipse启动项目正常,放到tomcat下单独启动就报错的 一例
  2. android 蓝牙和wifi存在冲突
  3. 如何设计物联网通信协议?
  4. [独立游戏]浅谈儿童编程儿童独立游戏开发者的未来
  5. miniblink载入html,一、【miniblink】使用miniblink加载网页
  6. Node.js(0)
  7. Python 计算变上限二重积分的数值模拟进阶
  8. 日常充电:教你成为程序员中的写作大师
  9. 根据父母的身高,体育锻炼,饮食习惯等,来预测孩子的身高
  10. 项目中高并发问题的解决方案