import os import streamlit as st from loguru import logger from app.core import settings def select_file(): ... def new_file(): new_file_name = st.session_state.new_file if not new_file_name.endswith('.py'): new_file_name = f'{new_file_name}.py' logger.debug(f"create new file: {new_file_name}") content = ''' #!/usr/bin/env python3 # -*- coding:utf-8 -*- import streamlit as st {add_content} st.write('Hello World!') ''' with open(os.path.join(settings.BASE_DIR, 'pages', new_file_name), 'w') as f: content = content.format(add_content=f"""st.markdown("# {st.session_state.new_file}")""").strip() st.write(f"create new file: {new_file_name}, write: ") st.code(content, language='python') f.write(content) with st.sidebar: pages = os.listdir(os.path.join(settings.BASE_DIR, 'pages')) pages = [{ 'filename': page, 'filepath': os.path.join(settings.BASE_DIR, 'pages', page) } for page in pages if page.endswith('.py') and page != '__init__.py'] option = st.selectbox( 'How would you like to be contacted?', pages, index=0, format_func=lambda x: x['filename'], on_change=select_file, key='page_file' ) st.write('You selected:', option) st.text_input('新建文件', on_change=new_file, key='new_file')