Spaces:
Sleeping

pythonconsole / app.py
raufoon's picture
Update app.py
c4f4a2f verified
Raw History Blame
3.48 kB
import gradio as gr
import subprocess
def sub_pattern_with_exclusion(fullpattern, excludedsubpattern, targetpattern, replacement, text):
import re
class emptymatch:
def __init__(self):
minus1 = lambda: -1
self.group = minus1; self.start = minus1; self.end = minus1;
matches1 = list(re.finditer(fullpattern, text))
matches2 = list(re.finditer(excludedsubpattern, text))
matches1.extend([emptymatch()]*(len(matches2)-len(matches1)))
matches2.extend([emptymatch()]*(len(matches1)-len(matches2)))
matches = []
for match1, match2 in zip(matches1, matches2):
if match1.start()>=0 and match1.start() == match2.start() and match1.end() == match2.end():
matches.append(match1)
modified_text = text
for match in reversed(matches):
modified_text = modified_text[:match.start()] + re.sub(targetpattern, replacement, match.group()) + modified_text[match.end():]
return modified_text
def run_code_with_inputs(code: str, inputs: str) -> str:
"""
Runs the provided Python code as a console program with the given inputs.
Parameters:
code (str): Python code to execute.
inputs (str): User inputs separated by newlines.
Returns:
str: Combined output from the program execution.
"""
filename = 'my_program.py'
echo = ''
fullpattern = r"\.? *input *\("
excludedsubpattern = r" *input *\("
targetpattern = "input"
replacement = "Input"
modified_code = sub_pattern_with_exclusion(fullpattern, excludedsubpattern, targetpattern, replacement, code)
modified_code = """
def Input(prompt=""):
res = input(prompt)
print(res)
return res
"""+modified_code
try:
with open(filename.removesuffix('.py')+'.py','wb') as file:
file.write(modified_code.encode('utf-8'))
file_path = file.name
input_data = inputs.replace("\\n", "\n")
process = subprocess.run(
["python", file_path],
input=input_data,
text=True,
capture_output=True
)
output = ''.join(echo)+process.stdout
errors = process.stderr
if errors:
return f"Errors:\n{errors}\n\nOutput:\n{output}"
return output
except Exception as e:
return f"An error occurred: {str(e)}"
# Define the Gradio interface
description = (
"This app allows you to input Python code for a console program "
"and provide a list of inputs separated by newlines. It will run the code "
"and return the entire program output."
)
with gr.Blocks(theme=gr.themes.Default(text_size=gr.themes.sizes.text_lg)) as demo:
gr.Interface(
fn=run_code_with_inputs,
inputs=[
gr.Code(label="Python Code", language="python", value="name=input(\"What's your name? \")\nprint(f\"Hello, {name}!\")"),
gr.Textbox(label="User Inputs", lines=5, value='Alice\nBob',placeholder="Enter inputs separated by newlines...")
],
outputs=gr.Code(
label="Program Output",
lines=10,
elem_id="output-box",
language=None
),
title="Python Console Runner",
description=description,
submit_btn=">_ Run",
clear_btn=None
)
demo.css = """
#output-box {
background-color: black;
font-family: monospace;
padding: 10px;
}
"""
if __name__ == "__main__":
demo.launch()