|
import streamlit as st |
|
import subprocess |
|
import os |
|
import tempfile |
|
import shutil |
|
|
|
|
|
if "temp_dir" not in st.session_state: |
|
st.session_state.temp_dir = tempfile.mkdtemp() |
|
|
|
temp_dir = st.session_state.temp_dir |
|
|
|
|
|
st.markdown(""" |
|
<style> |
|
.terminal { |
|
background-color: #1e1e1e; |
|
color: #00ff00; |
|
font-family: monospace; |
|
padding: 10px; |
|
border-radius: 5px; |
|
overflow-y: auto; |
|
max-height: 300px; |
|
} |
|
.terminal-input { |
|
background-color: #1e1e1e; |
|
color: #00ff00; |
|
font-family: monospace; |
|
border: none; |
|
outline: none; |
|
padding: 10px; |
|
width: 100%; |
|
border-radius: 5px; |
|
} |
|
.stButton>button { |
|
background-color: #4CAF50; |
|
color: white; |
|
padding: 10px 20px; |
|
border: none; |
|
border-radius: 5px; |
|
cursor: pointer; |
|
} |
|
</style> |
|
""", unsafe_allow_html=True) |
|
|
|
|
|
st.title("Google Colab-like Terminal in Streamlit") |
|
|
|
|
|
st.subheader("Terminal") |
|
if "output" not in st.session_state: |
|
st.session_state.output = "" |
|
|
|
|
|
st.markdown(f'<div class="terminal">{st.session_state.output}</div>', unsafe_allow_html=True) |
|
|
|
|
|
command = st.text_input("Enter your command:", placeholder="e.g., pip install numpy") |
|
|
|
|
|
if st.button("Run"): |
|
try: |
|
|
|
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" |
|
|
|
|
|
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.") |
|
|
|
|
|
def cleanup(): |
|
shutil.rmtree(temp_dir, ignore_errors=True) |
|
|
|
st.on_session_end(cleanup) |