How do I copy a string to the clipboard on Windows using Python?

后端 未结 23 2833
温柔的废话
温柔的废话 2020-11-22 03:13

I\'m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Pytho

相关标签:
23条回答
  • 2020-11-22 03:29

    You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows.

    0 讨论(0)
  • 2020-11-22 03:31

    You can use module clipboard. Its simple and extremely easy to use. Works with Mac, Windows, & Linux.
    Note: Its an alternative of pyperclip

    After installing, import it:

    import clipboard
    

    Then you can copy like this:

    clipboard.copy("This is copied")
    

    You can also paste the copied text:

    clipboard.paste()
    
    0 讨论(0)
  • 2020-11-22 03:33
    from Tkinter import Tk
    clip = Tk()
    
    0 讨论(0)
  • 2020-11-22 03:34

    Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:

    import subprocess
    subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value                                                                     
    0 讨论(0)
  • 2020-11-22 03:36

    Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

    If all you need is to put some text to system clipboard, this will do it:

    from Tkinter import Tk
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append('i can has clipboardz?')
    r.update() # now it stays on the clipboard after the window is closed
    r.destroy()
    

    And that's all, no need to mess around with platform-specific third-party libraries.

    If you are using Python 3, replace TKinter with tkinter.

    0 讨论(0)
  • 2020-11-22 03:36

    This is the improved answer of atomizer.

    Note 2 calls of update() and 200 ms delay between them. They protect freezing applications due to an unstable state of the clipboard:

    from Tkinter import Tk
    import time     
    
    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append('some string')
    
    r.update()
    time.sleep(.2)
    r.update()
    
    r.destroy()
    
    0 讨论(0)
提交回复
热议问题