Run selected text only
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!
You can use
editormodule to get selected text range and then split the lines into a list. last you should be able to iterate the list and use
execto 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.
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.
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!
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
site-packages-3directory (add to it if you already have something there).
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!!