Your Turn: A Script that Runs Scripts You Enter

A script that can run Python scripts embedded in strings opens up a lot of possibilities.  Cybersecurity activities rely heavily on a computer-connected micro:bit that radio-transmits strings with commands to a remote cyber:bot.  Since scripts can be embedded in strings, it might be possible for you to update your cyber:bot robot's script on the fly!  One challenge will be to prevent hackers from doing that to your cyber:bot for their own reasons!

This simple script accepts Python statements that you enter.  After you have entered the last Python statement, type run and press Enter to execute the script. 

Example script: embed_your_turn

  • Enter this script and save it as embed_your_turn.  
  • Flash the script into the micro:bit.
# embed_your_turn

from microbit import *

sleep(1000)

s = ""
t = ""

while True:
    s = input("> ")
    if(s != 'run'):
        t = t + s + "\n"
    else:
        exec(t)
        t = ""
  • Open the terminal.
  • Type this into the terminal:
    print("Hello!")
    run
  • Now, try this:
    print("Hello!")
    print("Hello again!")
    run
  • One more, and make sure to add four leading spaces for each indented statement:
    for(n in range(6)):
        print("n = ", n)
        sleep(250)
    run

Did each different script you entered execute in the terminal?

 

How it Works

The script starts by creating empty strings named s and script.  The s string receives each line you type, and the script string stores the actual script consisting of all the statements you type.

s = ""
script = ""

In the main loop, the s variable prompts for input from you by displaying a > prompt.  When you type a Python statement and press Enter, that statement gets stored in s.  

while True:
    s = input("> ")

The if...else… statement checks to see if what you typed does not match the string "run".  When it does not match, it assumes you have typed a statement and uses script = script + s + "\n" to append your statement and add a newline character to any previous statements you might have typed.  

     if(s != 'run'):
        script = script + s + "\n"

When you do type run and press Enter, the exec(script) function call runs the Python script you typed.  Then script = "" sets the script variable to an empty string so that you are starting over with an empty script.

    else:
        exec(script)
        script = ""