Skip to content

Instantly share code, notes, and snippets.

@markizano
Created February 16, 2024 04:15
Show Gist options
  • Save markizano/473c0ca71257c4a9f7ace65b400cc45e to your computer and use it in GitHub Desktop.
Save markizano/473c0ca71257c4a9f7ace65b400cc45e to your computer and use it in GitHub Desktop.
Clipboard command to convert English to Spanish and back.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Usage: I created a symlink to this file as ~/bin/es2en and ~/bin/en2es, but you can do this with any country code pairs.
# I put this in my `~/.fluxbox/keys`
# Mod4 Shift E :Exec /home/markizano/bin/es2en
# Mod4 Shift S :Exec /home/markizano/bin/en2es
#
# Restart fluxbox and now I can Win+Shift+E for English
# Win+Shift+S for Spanish
import io, os, sys
import subprocess
from select import select
import kizano
log = kizano.getLogger(__name__)
def main():
# Determine what language we are using by the name of the script.
# Symlink/hardlink to the same script and it'll translate for you!
ilang, olang = os.path.basename(sys.argv[0]).split('2')
arg = ' '.join(sys.argv[1:]) or ''
log.debug(arg)
if not arg:
stdin = sys.stdin.read() if select([sys.stdin], [], [], 0.0)[0] else ''
else:
stdin = ''
if not arg and not stdin:
clip = subprocess.check_output(['xclip', '-sel', 'c', '-o']).decode()
else:
clip = ''
to_translate = clip or stdin or arg
if not to_translate:
log.error('Nothing to translate?')
return 1
log.info(f'In lang: {ilang} ; out lang: {olang} ; Translating: {to_translate}')
trans = subprocess.Popen(['trans', '-b', '-s', ilang, '-t', olang], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
trans.stdin.write(to_translate.encode())
tout, terr = trans.communicate()
log.info(f'Translated: {tout.decode("utf-8")}')
xclipc = subprocess.Popen(['xclip', '-sel', 'c'], stdin=subprocess.PIPE)
xclipc.communicate(input=tout)
xclipp = subprocess.Popen(['xclip', '-sel', 'p'], stdin=subprocess.PIPE)
xclipp.communicate(input=tout)
return 0
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment