Skip to content

Commit

Permalink
Merge pull request #257 from vertliba/fix-wsl-encoding
Browse files Browse the repository at this point in the history
Fixed WSL Clipboard Handling
  • Loading branch information
asweigart authored Jun 18, 2024
2 parents 0eebe51 + 6dba64a commit 4eb7254
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/pyperclip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"""
__version__ = '1.9.0'

import base64
import contextlib
import ctypes
import os
Expand Down Expand Up @@ -491,21 +492,32 @@ def paste_windows():


def init_wsl_clipboard():

def copy_wsl(text):
text = _PYTHON_STR_TYPE(text) # Converts non-str values to str.
p = subprocess.Popen(['clip.exe'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
p.communicate(input=text.encode('utf-16le'))

def paste_wsl():
ps_script = '[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((Get-Clipboard -Raw)))'

# '-noprofile' speeds up load time
p = subprocess.Popen(['powershell.exe', '-noprofile', '-command', 'Get-Clipboard'],
p = subprocess.Popen(['powershell.exe', '-noprofile', '-command', ps_script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
stdout, stderr = p.communicate()
# WSL appends "\r\n" to the contents.
return stdout[:-2].decode(ENCODING)

if stderr:
raise Exception(f"Error pasting from clipboard: {stderr}")

try:
base64_encoded = stdout.decode('utf-8').strip()
decoded_bytes = base64.b64decode(base64_encoded)
return decoded_bytes.decode('utf-8')
except Exception as e:
raise RuntimeError(f"Decoding error: {e}")

return copy_wsl, paste_wsl

Expand Down

0 comments on commit 4eb7254

Please sign in to comment.