Forum Archive

Run selected text only

etalamo

Hi all,

Sorry for the newbie question, how can I run selected text (code) only instead of the full script?

Is there a keyboard shortcut?

Thanks a lot!

Eduardo

stephen

@etalamo

You can use editor module to get selected text range and then split the lines into a list. last you should be able to iterate the list and use exec to run each line. Alterativly you could create a temp script at run time then write the selected code to that script then run the scriot. just make ure to save the stream and close it.

if you need an example i can write one up for you but this should get you in the right direction.

mikael

@etalamo, what @stephen said, except even simpler:

import editor

start, end = editor.get_selection()
exec(editor.get_text()[start:end]) 

With this open, go to wrench menu, Edit it and add (+) this script as something you can then run from the wrench menu on your selected piece of code.

If you use an external keyboard, it is possible to tie this to a key combo.

etalamo

Thank you very much, it worked perfectly!

@mikael yes I’m using a bluetooth keyboard, do you know how can I tie it to a keyboard shortcut?

Again, thanks a lot!

mikael

@etalamo, I think the simplest way right now would be to install Black Mamba with the 1-liner here.

Then you create script like this (sets the magic key to be ⌘E):

import editor

from blackmamba.uikit.keyboard import (
    register_key_command, UIKeyModifier
)


def exec_selected():
    start, end = editor.get_selection()
    exec(editor.get_text()[start:end])


register_key_command(
    'e',
    UIKeyModifier.COMMAND,
    exec_selected,
    'Execute selected code'  # Optional discoverability title (hold down Cmd)
)

If that works as it should, place the code above in a file called pythonista_startup.py In the site-packages-3 directory (add to it if you already have something there).

etalamo

Hi @mikael thank you.

Unfortunately this last step didn’t work (I tried with different shortcut options). Nevertheless, Pythonista automatically adds a shortcut (I discovered it while holding the Command button down).

It’s not the simplest shortcut but at least I have one :)

Anyway, thank you for your help!!