使用pyperclip将新行添加到剪贴板?

时间:2014-06-04 12:28:13

标签: python clipboard

我使用pyperclip(允许你把东西放在剪贴板中的python模块),虽然它有利于放置单行,但如果我想让用户复制多行呢?放' / n'只复制' / n'直接进入字符串。我还可以做些什么?这是pyperclip的windows函数:

def winSetClipboard(self, text):
    text = str(text)
    GMEM_DDESHARE = 0x2000
    ctypes.windll.user32.OpenClipboard(0)
    ctypes.windll.user32.EmptyClipboard()
    try:
        # works on Python 2 (bytes() only takes one argument)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)  # @UndefinedVariable
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)  # @UndefinedVariable
    pchData = ctypes.windll.kernel32.GlobalLock(hCd)  # @UndefinedVariable
    try:
        # works on Python 2 (bytes() only takes one argument)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
    ctypes.windll.kernel32.GlobalUnlock(hCd)  # @UndefinedVariable
    ctypes.windll.user32.SetClipboardData(1, hCd)
    ctypes.windll.user32.CloseClipboard()

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,'\n'是换行符的正确转义。此外,Windows行结尾为'\r\n'