Take code input from user

I am trying to build an app which uses two files main.py and strategy.py. The main.py is what runs first and it imports a class from strategy.py. I want to take the python code for the strategy.py as an input from the user.

I tried using

user_input = st.text_area("label goes here", default_code_goes_here)

however when I run I keep getting a syntax error, perhaps the indentations aren’t being processed properly at some point.
Is there a way I can have a basic text editor (possibly with syntax highlighting ) and take the input from there and eval it?

I also tried ace-editor, it gives me the right text editor but the problem is that I cant evaluate the content.

Here is an image of this error :

As a quick solution, I continued with the ace-editor approach and just saved the content in a random file, imported it and deleted it after execution. Here’s the sample code :

import random, string
import importlib
import os

strategy_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) 
with open(strategy_name+'.py', 'w') as the_file:
TestStrategy = getattr(importlib.import_module(strategy_name), 'TestStrategy')

# do stuff
if os.path.exists(strategy_name+'.py'):
  print("The file does not exist")

If someone finds a neater way, please let me know!

1 Like