Copy string - Python

帅比萌擦擦* 提交于 2019-12-07 11:55:11

问题


Ok guys I imagine this is easy but I can't seem to find how to copy a string. Simply COPY to the system like CTRL+C on a text.

Basically I want to copy a string so I can for example, lets say, paste(ctrl+v).

Sorry for such a trivial question, haha.


回答1:


This depends a lot on the OS. On Linux, due to X's bizarre selection model, the easiest way is to use popen('xsel -pi'), and write the text to that pipe.

For example: (I think)

def select_xsel(text):
    import subprocess
    xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
    xsel_proc.communicate(some_text)

As pointed out in the comments, on a Mac, you can use the /usr/bin/pbcopy command, like this:

xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)

If you want to support different OSes, you could combine different solutions with os.name to determine which method to use:

import os, subprocess
def select_text(text):
    if os.name == "posix":
        # try Mac first
        try:
            xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
        except:
            # try Linux version
            xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
    elif os.name == "nt":
        # Windows...



回答2:


For Windows, you use win32clipboard. You will need pywin32.

For GTK (at least on GNU/Linux), you can use pygtk.

EDIT: Since you mentioned (a bit late) you're using wxPython, they actually have a module for this too, wx.Clipboard.




回答3:


For Windows, you can do this and it's much easier than creating a new subprocess etc...




回答4:


For a multi-platform solution you will need to use a cross-platform framework like wxPython or PyQt - they both have support for reading and writing to the system clipboard in a platform independent way.



来源:https://stackoverflow.com/questions/2614975/copy-string-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!