Created
January 23, 2023 21:02
-
-
Save Lokno/7632bee9b5dda3440bfa8ea3680603d9 to your computer and use it in GitHub Desktop.
Executes the contents of the clipboard as Python and returns the result to the clipboard
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Executes the contents of the clipboard as Python and returns the result to the clipboard | |
# Uses eval() if single-line and uses compile() and exec() if multi-line | |
# Will attempt to handle a limited number of NameError exceptions | |
# Obvious at your own risk and know what you're doing caveats | |
import pyperclip | |
import traceback | |
import contextlib | |
import sys | |
import re | |
from io import StringIO | |
from math import * | |
import_attempts = 3 | |
re_name = re.compile("name '([^']+)' is not defined") | |
clipboard = pyperclip.paste().strip() | |
def exec_str(s): | |
output = '' | |
if s.find('\n') >= 0: | |
with StringIO() as h, contextlib.redirect_stdout(h): | |
cc = compile(s, '<string>', 'exec') | |
eval(cc) | |
output = h.getvalue() | |
else: | |
output = str(eval(s)) | |
return output | |
def handle_name_error(e,s): | |
m = re_name.match(e.args[0]) | |
matched = False | |
print('handling') | |
if m: | |
matched = True | |
module_name = m.group(1) | |
if module_name == 'np': | |
import_line = 'import numpy as np\n' | |
elif module_name == 'plt': | |
import_line = 'import matplotlib.pyplot as plt\n' | |
else: | |
import_line = f'import {module_name}\n' | |
if s.find('\n') < 0: | |
s = f'{import_line}print({s})' | |
else: | |
s = import_line+s | |
print(s) | |
return matched,s | |
output = '' | |
success = False | |
while not success and import_attempts > 0: | |
try: | |
output = exec_str(clipboard) | |
success = True | |
except NameError as e: | |
import_attempts -= 1 | |
m,clipboard = handle_name_error(e,clipboard) | |
if not m: | |
output = traceback.format_exc() | |
break | |
except: | |
output = traceback.format_exc() | |
break | |
pyperclip.copy(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment