如何使用pyperclip向剪贴板添加换行符?
我正在使用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 个回答
2
正如评论中提到的,'\n'
是表示换行的正确写法。另外,Windows系统中的换行符是 '\r\n'
。