Skip to content

Instantly share code, notes, and snippets.

@upsuper
Created December 23, 2011 14:04
Show Gist options
  • Save upsuper/1514297 to your computer and use it in GitHub Desktop.
Save upsuper/1514297 to your computer and use it in GitHub Desktop.
Send keys to clipboard or input directly (now only for Mac OS X and partly Linux)
# - * - coding: UTF-8 - * -
import subprocess
def macosx_set_clipboard(text):
p = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
p.communicate(text)
def macosx_send_keys(text):
text = text.replace('\\', '\\\\').replace('"', '\\"')
code = 'tell application "System Events" to keystroke "%s"'
p = subprocess.Popen('osascript', stdin=subprocess.PIPE)
code = code % (text, )
p.communicate(code)
def xte_send_keys(text):
subprocess.call(['xte', 'str ' + text])
def unsupported_platform(*args, **kws):
raise 'Unsupported platform'
set_clipboard = unsupported_platform
send_keys = unsupported_platform
import platform
_system = platform.system()
if _system == 'Darwin':
set_clipboard = macosx_set_clipboard
send_keys = macosx_send_keys
# pre send to accelerate sendkeys
_p = subprocess.Popen('osascript', stdin=subprocess.PIPE)
_p.stdin.write('tell application "System Events" to keystroke ""')
_p.stdin.close()
elif _system == 'Linux':
def prog_exists(prog):
import os
import os.path as path
for p in os.environ["PATH"].split(os.pathsep):
exe_file = path.join(p, prog)
if path.exists(exe_file):
return True
return False
if prog_exists('xte'):
send_keys = xte_send_keys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment