Coder Social home page Coder Social logo

pyperclip's Introduction

Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with Python 2 and 3.

Install on Windows: pip install pyperclip

Install on Linux/macOS: pip3 install pyperclip

Al Sweigart [email protected] BSD License

Example Usage

>>> import pyperclip
>>> pyperclip.copy('The text to be copied to the clipboard.')
>>> pyperclip.paste()
'The text to be copied to the clipboard.'

Currently only handles plaintext.

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" (Note: xsel does not always seem to work.)

Otherwise on Linux, you will need the qtpy or PyQT5 modules installed.

Support

If you find this project helpful and would like to support its development, consider donating to its creator on Patreon.

pyperclip's People

Contributors

aniketp avatar ankostis avatar asweigart avatar ctimmerman avatar dependabot[bot] avatar digenis avatar drakulavich avatar dvincentwest avatar gato avatar haydenflinner avatar hugovk avatar masajxxx avatar mgorny avatar mgunyho avatar mhils avatar modax avatar nik012003 avatar pgajdos avatar pirateofandaman avatar pwnage101 avatar smartmanoj avatar sscherfke avatar stefandevai avatar stephenfin avatar timgates42 avatar tleonhardt avatar tmr232 avatar utgwkk avatar vertliba avatar zedgr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyperclip's Issues

Cannot paste characters like ñ on os x

This bug report comes from this user comment:

In Lecture 29, I have a large PDF directory with phone numbers and emails. I have tested the script and it works on one page with phone numbers and emails, but when I do the whole PDF (e.g. Ctrl-A, then Ctrl-C), I get the following error:

File "phone_email_ex.py", line 33, in

text = pyperclip.paste()

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pyperclip/clipboards.py", line 22, in paste_osx

return stdout.decode('utf-8')

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd2 in position 23578: invalid continuation byte

I think it is an issue of encoding, but where do I find the issue in the data (has to be some random character like an "ñ") and where do I put the appropriate encoding after importing the encodings module. It looks like it should be during the pyperclip.paste() function.

pyperclip.paste() raises TypeError on OS X

pyperclip.paste() raises a TypeError on OS X:

>>> pyperclip.paste()
fooTraceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/name/.virtualenvs/mpw/lib/python3.4/site-packages/pyperclip/__init__.py", line 111, in _pasteOSX
    return bytes.decode(stdout)
TypeError: descriptor 'decode' requires a 'bytes' object but received a 'NoneType'

I think the problem is using subprocess.Popen. It seems to bypass stdout, so p.communicate() returns (None, None). It works if you use pwd = subprocess.check_output(['pbcopy', 'r']). However, this was only added in Python 2.7 – I’m not sure if Python 2.6 is still important for you or not.

"Cannot connect to X server"

We have multiple mitmproxy users who are apparently facing an issue caused by pyperclip trying to initialize some GUI framework (?) and then sys.exit()ing (?): mitmproxy/mitmproxy#701 (comment)

Any ideas/pointers what could cause this? A fix for this would be highly appreciated. 😃

Why it calls PyQt4 instead of xclip?

I'm trying use pyperclip to make a clipboard monitor. xclip has been installed on my Linux system, but pyperclip seem to use PyQt4 and show the error message:

QObject::startTimer: QTimer can only be used with threads started with QThread
[1]    8682 segmentation fault  ./clipdown.py

Pyperclip paste not working

Hello I've been attempting to use pyperclip it copies fine but when asked to paste. Always respond with something like this...

============== RESTART: C:\Users\212419205\Desktop\testing24.py ==============

Hopefully you can help me and I would really appreciate it

Import ctypes.wintypes on Linux

Currently pyperclip imports all clipboards in the head of module:

from .clipboards import (init_gtk_clipboard, init_klipper_clipboard, init_osx_clipboard,
                         init_qt_clipboard, init_xclip_clipboard, init_xsel_clipboard, init_no_clipboard)
from .windows import init_windows_clipboard

I think it's not necessary, because clipboard types are platform specific. So on Linux you will get an error from wintypes. It's better to import only platfrom specific functions.

>>> import pyperclip
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pyperclip/__init__.py", line 30, in <module>
    from .windows import init_windows_clipboard
  File "pyperclip/windows.py", line 8, in <module>
    from ctypes.wintypes import HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE
  File "/usr/lib/python2.7/ctypes/wintypes.py", line 23, in <module>
    class VARIANT_BOOL(_SimpleCData):
ValueError: _type_ 'v' not supported

What are your opinions, guys?

[Python 3.4.4] Pyperclip.paste not working in OS X 10.10.5 Yosemite 64 bit with Firefox

Hi,
I have the pyperclip module installed and python version is 3.4.4
I am running a python script does the following in OS X 10.10.5 Yosemite 64 bit English(US) :

  1. Open Firefox
  2. Copy some text from the google search results
  3. Call pyperclip.paste in the script to get the clipboard text.

It keeps throwing the following error:
guid = pyperclip.paste()

File "/site-packages/pyperclip/clipboards.py", line 20, in paste_osx
stdout=subprocess.PIPE, close_fds=True)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 859, in init
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 1463, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'pbpaste'

The same script works in Chrome browser in OS X.
It works in chrome, firefox browser in windows also.

I am not sure why this is happening specific to firefox run.

Can someone please help me on this?

pip install fails on Cygwin

When using pip install pyperclip on latest Cygwin (Windows 10) using Python 3.4.3 installation fails:

Collecting pyperclip
  Using cached pyperclip-1.5.25.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-323sgh0o/pyperclip/setup.py", line 8, in <module>
        version=__import__('pyperclip').__version__,
      File "/tmp/pip-build-323sgh0o/pyperclip/pyperclip/__init__.py", line 99, in <module>
        copy, paste = determine_clipboard()
      File "/tmp/pip-build-323sgh0o/pyperclip/pyperclip/__init__.py", line 53, in determine_clipboard
        return init_windows_clipboard(cygwin=True)
      File "/tmp/pip-build-323sgh0o/pyperclip/pyperclip/windows.py", line 26, in init_windows_clipboard
        from ctypes.wintypes import (HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND,
      File "/usr/lib/python3.4/ctypes/wintypes.py", line 20, in <module>
        class VARIANT_BOOL(ctypes._SimpleCData):
    ValueError: _type_ 'v' not supported

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-323sgh0o/pyperclip

Missing way to delete the clipboard after pastes

You should be able to instruct the clipboard to delete its content after some number of pastes - typically 1.

To my understanding, xclip allows a --loop option that let you specify the number of pastes to allow before deleting the clipboard. (Not sure though, I'm not on a Linux box right now).

Use case of this feature: an application that produces secrets might want to copy the secret directly into the clipboard instead of ask the user to copy - for usability reasons. Yet, leaving the content after it has been consumed sounds bad.

Possible API:

pyperclip.copy("Clipboard content", npaste=5) # Allowing 5 pastes

Load both the X clipboard *and* the GTK one.

Hi,

I see that pyperclip will load the first clipboard it can using whichever tool it can. The code looks like this:

    # Set one of the copy & paste functions.
    if xclipExists:
        _functions = 'xclip command' # for debugging
        paste = _pasteXclip
        copy = _copyXclip
    elif gtkInstalled:
        _functions = 'gtk module' # for debugging
        paste = _pasteGtk
        copy = _copyGtk
    elif ...

This means, on a posix system, we load either the X clipboard (a.k.a. the PRIMARY clipboard ), or the GTK one (a.k.a. the CLIPBOARD clipboard).

I would like to load both of these clipboards.

I suppose we would need _copyGtkAndXclip and a pasteGtkAndXclip functions.

Pyperclip not working on MacOS Sierra?

Hello, I'm going through Automate the boring stuff with Python and I couldn't make pyperclip work for me.

If I run pyperclip.copy('Hello World') and then pyperclip.paste() all I get is u''. I know the 'u' is for unicode, but why isn't it working with my clipboard?

I'm sorry if the question is a bit vague. I'm still pretty noob.

pyperclip.copy() returns None

import pyperclip
print(repr(pyperclip.copy('Text')))

Returns

[Almoullim] /home/ali/Dev/python3 % python3 ext.py
None

if i use pyperclip from the terminal it works, but when i use it inside a .py file it doesn't

Pyperclip does not persist if called from script

I want to store something into the clipboard via a python script.
It's basically just pyperclip.copy('text'). I'm using Fedora 21 with AwesomeWM. I read here that a clipboard manager is needed to store it permanent in the clipboard. I installed parcellite. It now works, if I use it in an terminal, via

$python
$>>> import pyperclip
$>>> pyperclip.copy('teststring')

BUT if I do the exact same thing in an script

import pyperclip
pyperclip.copy('teststring')

and execute this script with python filename.
It won't get stored in the clipboard.

Any ideas on where the error may happen?

Not Support Chinese (Can be fixed)

When os clipboard have chinese words, clipboards.py has an error (line:16) .
1
But I Fixed it Like this:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

use PyObjC if available

rather than forking a new process for every copy/paste it'd be nice to use the os libraries (if available)

http://blog.carlsensei.com/post/88897796

Those are available if you have this
https://pythonhosted.org/pyobjc/install.html

import Foundation, AppKit

def pbcopy(s):
    "Copy string argument to clipboard"
    newStr = Foundation.NSString.stringWithString_(s).nsstring()
    newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
    board = AppKit.NSPasteboard.generalPasteboard()
    board.declareTypes_owner_([AppKit.NSStringPboardType], None)
    board.setData_forType_(newData, AppKit.NSStringPboardType)

def pbpaste():
    "Returns contents of clipboard"
    board = AppKit.NSPasteboard.generalPasteboard()
    content = board.stringForType_(AppKit.NSStringPboardType)
    return content

PyQt4 broken on Ubuntu

The PyQt4 implementation is broken on Ubuntu 14.04, but I don't necessarily think it's pyperclips fault:

~/ λ python3                                                                                                                                                              
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4.QtGui import QApplication
>>> QApplication([]).clipboard().setText("test")
[1]    2441 segmentation fault (core dumped)  python3

Either way, I would really prefer it if xclip was prioritized over PyQt4, and/or being able to blacklist implementations in the preference list.

Ubuntu Package lists PyQt4 and xclip as dependencies.

Not directly a pyperclip issue, but the pyperclip Ubuntu package declares PyQt4 and xclip as a dependency. As a consequence, all packages that depend on pyperclip transitively depend on libqt4, libx11, etc.. We had a few mitmproxy users who were not so amused by this (especially if you install it on Ubuntu Server...), and I'd love to start a discussion how this could be tackled. As I see it, pyperclip should list none of those as a dependency.

http://packages.ubuntu.com/de/xenial/python-pyperclip

cc @sdelafond

pyperclip module not working at all???

I am learning Python by first reading Automate the Boring Stuff With Python and have just got to Chapter 6 and am trying to get the pyperclip module to work. I have followed the instructions and installed / uninstalled on two different systems ( Win 7 x64 and Win 10 x64, Python v3.5.1 ) and can get the following lines to run if typed directly into the interactive shell :

import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste()

But when using IDLE and trying to run using F5 + Save, it gives the error below :

================================ RESTART: C:\Python\pyperclip.py ================================
Traceback (most recent call last):
File "C:\Python\pyperclip.py", line 1, in
import pyperclip
File "C:\Python\pyperclip.py", line 2, in
pyperclip.copy('Hello world!')
AttributeError: module 'pyperclip' has no attribute 'copy'

Any help would be greatly appreciated.

Thanks!!!

Use TKinter if possible

Most python deployments have TKinter. This should be way more portable than usage of gtk / qt / xclip and xsel as well a much faster than popen

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk

def clip_set(text):
     r=Tk()
     r.withdraw()
     r.clipboard_clear()
     r.clipboard_append(text)
     r.destroy()


def clip_get():
     r=Tk()
     r.withdraw()
     ttt = r.clipboard_get()
     r.destroy()
     return ttt

Cygwin copy fails

I am running:
CYGWIN_NT-6.1 1.7.35(0.287/5/3) x86_64 Cygwin
Python 2.7.8 [GCC 4.8.3]

The line:

>>> pyperclip.copy('teststring')

produces the error:

LookupError: unknown encoding: mbcs

Pyperclip not working in Win10 Python 3.5.3

Big fan of your book, by the way! But regarding Pyperclip -

Pyperclip installs fine. Copies OK to the Win clipboard. BUT --

When I try to paste anything FROM the clipboard, whether copied from within Pyperclip or from within Win, as in:

pyperclip.paste()

I get this:

'<function init_windows_clipboard..paste_windows at 0x000002CD1B289400>'

This is not quite what I need. Do you have any suggestions? I really do need to get this working.

Pyperclip not working on macOS

Trying to use the pyperclip but it does not seem to work. I've tried troubleshooting the problem all over, but can't find a solution.

Whenever i use pyperclip.copy("Hello World"), the text is not copied to my clipboard. The program works in IDLE, but not using my terminal command line. I've sudo pip3 installed the module, and i am using the #! /usr/.../env python3 that is listed in the book to use the module. I am getting really frustrated with this problem, as i've been stuck on the project for quite some time. Any help would be greatly appreciated. Thanks in advance.

#EDIT# I've found the solution.

I was using tmux, and pyperclip would not work. The second i stopped tmux, the module started working.

OSError on Win10 Py 3.5

A user reported this exception on Windows 10, Python 3.5:

========= RESTART: C:\Users\Russ\Desktop\python_work
Traceback (most recent call last):
File "C:\Users\Russ\Desktop\python_work\pyperclip.py", line 70, in winSetClipboard
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
TypeError: string argument without an encoding

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Russ\Desktop\python_work\ceasarCipher.py", line 52, in
pyperclip.copy(translated)
File "C:\Users\Russ\Desktop\python_work\pyperclip.py", line 73, in winSetClipboard
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
OSError: exception: access violation writing 0x0000000000000000

Copying fails/disabled after 2nd copy iteration

First copy works fine (I am using this in conjunction with torque's aae-export (https://gist.github.com/torque/6453947) with Blender!

Exporting the data the first time around works well (i.e. copying it), but the second time around it fails with the following error generated by the export script.
aae error

The Windows clipboard is disabled from this point on until Blender!/pyperclip is closed. I am unable to copy or paste anything as there seems to be "no" clipboard for Windows to make use of anymore.

Im using Windows 7 Professional x64, pyperclip 1.5.8, and Blender 2.7.3

Add some informative top-level files to the PyPI zip file

Please consider adding the following informative top-level files to the tarball/zip file distributed via PyPI.

AUTHORS.txt
CHANGES.txt
LICENSE.txt
README.md

This just requires a minor/trivial edit to the MANIFEST.in so I avoid a PR here.

KDE 5 Klipper broken

I will shortly attempt to see why this is occurring, but here is what happens if you try to use the latest release under KDE 5. (Please note this still works under KDE 4)

---------- Data ----------

13:33 $ python -m unittest basicTests
Testing on: Python 2.7.9 - (KDE Klipper) - qdbus (external)                                                                                                       
Cannot find '.setClipboardContents' in object /klipper at org.kde.klipper                                                                                         
Service 'org.kde.klipper' does not exist.                                                                                                                         
FCannot find '.setClipboardContents' in object /klipper at org.kde.klipper                                                                                        
Service 'org.kde.klipper' does not exist.                                                                                                                         
F                                                                                                                                                                 
======================================================================
FAIL: test_copyPaste (basicTests.TestCopyPaste)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "basicTests.py", line 15, in test_copyPaste
    self.assertEqual(pyperclip.paste(), msg)
AssertionError: u'' != 'The quick brown fox jumped over the yellow lazy dog.'

======================================================================
FAIL: test_randomCopyPaste (basicTests.TestCopyPaste)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "basicTests.py", line 24, in test_randomCopyPaste
    self.assertEqual(pyperclip.paste(), msg)
AssertionError: u'' != 'kioqdZBItNwtDuIYvfqjjoxIu8JWBUU1QCJgFPRYOWng5lVipdXSZ59s5K8cb04GWQyfTRltS3XhG3OGxDC40XnxhYLkDeH7AZ2Oy1CTo3F8NMjlKPQEAMzBe62607pcTwmEJ2s1UgaHzavNwshSVFfLkP4AKemr769rzbubncriqMaLmREdvVpyH9'

----------------------------------------------------------------------
Ran 2 tests in 0.072s

FAILED (failures=2)

Exception on copy on Windows

Hi, I'm using Windows Server 2008 SP2 x64 Enterprise, Python 2.7.6, and Pyperclip 1.5.6. When calling 'copy', I get:

In [1]: import pyperclip

In [2]: pyperclip.copy("a")
---------------------------------------------------------------------------
ArgumentError                             Traceback (most recent call last)
<ipython-input-2-9a2c839cf2a4> in <module>()
----> 1 pyperclip.copy("a")

c:\cygwin\home\administrator\powertools\eggs\pyperclip-1.5.6-py2.7.egg\pyperclip\__init__.pyc in _copyWindows(text)
     45         if not isinstance(text, str):
     46             text = text.decode('mbcs')
---> 47     d.user32.OpenClipboard(None)
     48     d.user32.EmptyClipboard()
     49     hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)

ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type

I don't know why, but I noticed that ctypes doesn't allow None to OpenClipboard, but passing '0' instead works:

In [3]: import ctypes

In [4]: ctypes.windll.user32.OpenClipboard(None)
---------------------------------------------------------------------------
ArgumentError                             Traceback (most recent call last)
<ipython-input-4-a325f2f33e77> in <module>()
----> 1 ctypes.windll.user32.OpenClipboard(None)

ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type

In [5]: ctypes.windll.user32.OpenClipboard(0)
Out[5]: 1

Do you think you could change None to 0 please?

Pyperclip does not work on Windows XP 32-bit

Pyperclip doesn't work on WIndows XP 32-bit (and possibly 64-bit too). When installing, the following output is received:

C:\Python34\Scripts>pip install pyperclip
Collecting pyperclip
  Using cached pyperclip-1.5.24.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "C:\DOCUME~1\admin\LOCALS~1\Temp\pip-build-ncweabkc\pyperclip\setup.p
y", line 8, in <module>
        version=__import__('pyperclip').__version__,
      File "C:\DOCUME~1\admin\LOCALS~1\Temp\pip-build-ncweabkc\pyperclip\pypercl
ip\__init__.py", line 103, in <module>
        copy, paste = determine_clipboard()
      File "C:\DOCUME~1\admin\LOCALS~1\Temp\pip-build-ncweabkc\pyperclip\pypercl
ip\__init__.py", line 53, in determine_clipboard
        return init_windows_clipboard()
      File "C:\DOCUME~1\admin\LOCALS~1\Temp\pip-build-ncweabkc\pyperclip\pypercl
ip\windows.py", line 75, in init_windows_clipboard
        wcscpy_s = ctypes.cdll.msvcrt.wcscpy_s
      File "C:\Python34\lib\ctypes\__init__.py", line 364, in __getattr__
        func = self.__getitem__(name)
      File "C:\Python34\lib\ctypes\__init__.py", line 369, in __getitem__
        func = self._FuncPtr((name_or_ordinal, self))
    AttributeError: function 'wcscpy_s' not found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\DOCUME~1\admin
\LOCALS~1\Temp\pip-build-ncweabkc\pyperclip

When I try to modify the code to use ctypes.cdll.msvcrt.wcscpy instead of ctypes.cdll.msvcrt.wcscpy_s, this quick fix just results in this error:

>>> import pyperclip
>>> pyperclip.copy('howdy')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\pyperclip\windows.py", line 142, in copy_windows
    if wcscpy_s(c_wchar_p(locked_handle), count, c_wchar_p(text)):
OSError: exception: access violation reading 0x00000006

This is probably an issue that wcscpy_s doesn't exist in the old msvcrt.dll. I was able to replicate this in a VM. I'm not sure if this can be fixed by updating the dll, but we should come up with a better solution than that.

Pyperclip not working with Django-1.11.2

Pyperclip is working fine in normal python programmes. However, when I use it in django-views. It shows the same Pyperclip exception: Pyperclip could not find a copy/paste mechanism for your system.

Here is the code snippet:

import pyperclip

@login_required()
def copy_nomi_link(request, pk):
    nomi_detail_url = 'https://' + DOMAIN_NAME + '/nominations/nomi_detail/' + str(pk) + '/'
    pyperclip.copy(nomi_detail_url)

    return HttpResponseRedirect(reverse('admin_portal'))

@asweigart Please suggest something. Thanks!

Copy fails

Hi,
I'm having a weird issue with pyperclip.
First copy succeeds, then I paste, also succeed.

Second copy fails. It fails on OpenClipboard() with getlasterror 1400, ERROR_INVALID_WINDOW_HANDLE
I'm using pyperclip in an Qt text/hex editor, and there is no simple way to reproduce it.

Extraneous output on Linux when doing paste() and clipboard is empty

If you do a pyperclip.paste() on Linux when the clipboard is empty, then pyperclip prints this extraneous line to stdout: Error: target STRING not available

This may only occur when using certain backends on Linux such as xclip, I haven't tested extensively enough to know if the same thing happens with other backends.

Regardless, the current behavior is undesirable. Various alternative behaviors would be reasonable, if nothing is available in the clipboard, including:

  • Return None
  • Return an empty str
  • Raise an exception which users can catch if they wish

P.S. Thanks for creating this nice and rather useful Python module ;-)

[Solved]Can't import into Python 3.6

Hi Sir,

pyperclip 1.5.27 runs well on Python 3.5 on Debian, but failed to import into 3.6 as following.

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

I have reinstalled it with pip3 but still failed. Will u upgrade to support it? MTKS

Save bitmap to clipboard

It would be nice if there was API that can save captured bitmaps to clipboard. Something that accepts PyCBitmap object from pywin32:

SetClipboardData(CF_BITMAP, dataBitMap)

Encoding on Windows

I ran into an error while trying to copy characters outside the ascii range (>128), and was wondering if it might be better to use encoding cp1252 for Windows, or perhaps even make the encoding a parameter for copy with a suitable default?

Unbelievable hack idea for Windows copy/paste fallback.

A lot of people are reporting problems with copy()/paste() on Windows 10. Pyperclip directly uses ctypes and the win32 api to do the copying and pasting. As an alternative fallback, if that fails, pyperclip could use clip.exe to copy the text. Clip.exe comes with Windows since Vista (XP doesn't have it, but the win32 approach seems to always work for XP).

There is no paste program unfortunately. HOWEVER, here's where my ridiculous plan comes in: There is an open source paste.exe here: http://www.c3scripts.com/tutorials/msdos/paste.html

Pyperclip could store this 4k executable binary as base64 inside its source code. When paste() is called, it can write this out, run it, then delete it. Performance would be terrible, but only if you were running paste constantly in a loop (which is not pyperclip's main case). File-writing and execution permissions would be another issue. Filename collisions would be another. There is, of course, a security issue (similar to tempnames) where an attacker could put in their own file that the Python script would end up running. (This issue currently exists with pyperclip on OS X, which calls pbcopy/pbpaste.)

Any other ideas why this shouldn't be added? Remember, this is a fallback in case the normal approach fails.

Error on Windows: OSError: exception: access violation writing 0x0000000000000000

I would like to use pyperclip to copy to clipboard and paste from it, but it seems that it is not working.

When I try to use pyperclip.copy("some string"), I get the following errors:

Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\site-packages\pyperclip__init__.py", line 68, in winSetClipboard
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
TypeError: string argument without an encoding

During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in
pyperclip.copy("hello")
File "C:\Program Files\Python 3.5\lib\site-packages\pyperclip__init__.py", line 71, in winSetClipboard
ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
OSError: exception: access violation writing 0x0000000000000000

On the other hand, when I use pyperclip.paste() even if I had copied something previously, I get nothing printed, and even sometimes python crashes.

I am using windows 10 and python 3.5. I have also tried with python 3.4.3.

I have asked a question on [StackOverflow][http://stackoverflow.com/questions/32763044/pyperclip-module-not-working], and someone suggested to use pyperclip.copy(b"somestring"), and in this case I just get the second error. After informing this result, he suggested to report this as an issue, so this is it.

Thanks in advance.

Please don't throw exceptions during import.

Hi,
import pyperclip should never throw an exception. Currently it raises an exception of type Exception or a RuntimeError on some systems.

Instead it's better to have the copy/paste functions raise an exception when it's called, if the platform is not supported. (But that should be a PyperclipException or something similar. Not Exception.)
Maybe we could also add another function platform_is_supported for checking.

See also: http://chrismorgan.info/blog/say-no-to-import-side-effects-in-python.html

Is this a change to which you are open, or should I fork? I'm willing to create a pull request.

Jonathan

could not find copy/paste mechanism

Tried all four solutions and they don't work on linux

Installed xsel and xclip still got same error
could not find a distribtion for gtk and PyQt4

test_copy_paste_unicode fails with 'ascii' codec can't encode character u'\u0ca0'

Here is the complete error:

======================================================================
ERROR: test_copy_paste_unicode (__main__.TestQt)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/test_copy_paste.py", line 64, in test_copy_paste_unicode
    self.assertEqual(self.paste(), msg)
  File "tests/../pyperclip/clipboards.py", line 52, in paste_qt
    return str(cb.text())
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0ca0' in position 0: ordinal not in range(128)

----------------------------------------------------------------------
Ran 56 tests in 0.063s

FAILED (errors=1, skipped=42)

This is with 1.5.24, on linux. My current locale is a UTF-8 one, so I'm not sure what's wrong.

Unable to install via pip

Hello!
I've tried to install it globally with sudo via pip but I get this error:

Command "python setup.py egg_info" failed with error code -11 in /tmp/pip-build-pnhz8pqb/pyperclip/

ArgumentError: argument 1: <class 'TypeError'>: wrong type

I install pyperclip-1.5.11 for Python 3.4 on Win7.

When I run following code:

import pyperclip
pyperclip.paste()

I meet following error:

C:\pyzo2015a\lib\site-packages\pyperclip\__init__.py in _pasteWindows()
     32     CF_UNICODETEXT = 13
     33     d = ctypes.windll
---> 34     d.user32.OpenClipboard(0 if PY2 else None)
     35     handle = d.user32.GetClipboardData(CF_UNICODETEXT)
     36     data = ctypes.c_wchar_p(handle).value

ArgumentError: argument 1: <class 'TypeError'>: wrong type

Please let me know what I should do to solve the problem.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.