import streamlit as st
import subprocess
import os
import tempfile
import shutil
# Set up a temporary working directory
if "temp_dir" not in st.session_state:
st.session_state.temp_dir = tempfile.mkdtemp()
temp_dir = st.session_state.temp_dir
# Custom CSS for Google Colab-like design
st.markdown("""
""", unsafe_allow_html=True)
# App title
st.title("Google Colab-like Terminal in Streamlit")
# Command execution area
st.subheader("Terminal")
if "output" not in st.session_state:
st.session_state.output = ""
# Display terminal output
st.markdown(f'
{st.session_state.output}
', unsafe_allow_html=True)
# Command input
command = st.text_input("Enter your command:", placeholder="e.g., pip install numpy")
# Execute the command
if st.button("Run"):
try:
# Execute the command and capture output
result = subprocess.run(command, shell=True, cwd=temp_dir, capture_output=True, text=True)
output = result.stdout if result.returncode == 0 else result.stderr
st.session_state.output += f"$ {command}\n{output}\n"
except Exception as e:
st.session_state.output += f"$ {command}\nError: {e}\n"
# File management
st.subheader("Files")
if st.button("Show Files"):
files = os.listdir(temp_dir)
if files:
st.write("Files in the working directory:")
for file in files:
file_path = os.path.join(temp_dir, file)
st.download_button(label=f"Download {file}", data=open(file_path, "rb"), file_name=file)
else:
st.write("No files found.")
# Cleanup temporary files when the session ends
def cleanup():
shutil.rmtree(temp_dir, ignore_errors=True)
st.on_session_end(cleanup)