250909 화요일반 코드
import streamlit as st
st.title("원킹의 스트림릿 연습장")
st.write("스트림릿의 기능을 이것저것 연습해 봅시다.")
st.success("이미지 넣기")
url = "https://i.ytimg.com/vi/OQZ8F4Szk88/hq720.jpg?v=68ac9993&sqp=-oaymwEhCK4FEIIDSFryq4qpAxMIARUAAAAAGAElAADIQj0AgKJD&rs=AOn4CLDG7bCAJ4UcELeHJBzoatzH0ahwXA"
st.image(url)
st.success("버튼 넣기")
word = " "
col1, col2 = st.columns(2)
if col1.button("사랑") : word = "사랑해요 !"
if col2.button("겸손") : word = "존경해요 !"
st.success(word)
Python
복사
run.py 코드
# run.py (프로젝트 루트에 저장)
# 사용: Streamlit 앱 파일 맨 위에 import run # 한 줄만 추가하세요.
import os
import sys
import subprocess
from typing import Optional
def _get_main_path() -> Optional[str]:
"""현재 인터프리터가 실행 중인 메인 스크립트 경로 반환(.py만 유효)."""
main = sys.argv[0]
if not main or not main.endswith(".py"):
return None
path = os.path.abspath(main)
return path if os.path.exists(path) else None
def _is_streamlit_runtime() -> bool:
"""이미 Streamlit 내부에서 실행 중인지 여부."""
return bool(os.environ.get("STREAMLIT_RUNTIME"))
def _is_self_rerun() -> bool:
"""우리가 재호출한 프로세스인지(재귀 방지 플래그)."""
return os.environ.get("SELF_STREAMLIT") == "1"
def _is_same_file(a: str, b: str) -> bool:
"""두 경로가 같은 파일인지 안전하게 비교."""
try:
return os.path.samefile(a, b)
except Exception:
return os.path.abspath(a) == os.path.abspath(b)
def _looks_like_streamlit_app(path: str) -> bool:
"""대상 파일이 Streamlit 앱처럼 보이는지(간단한 임포트 탐지)."""
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
head = f.read(8192)
return ("import streamlit" in head) or ("from streamlit" in head)
except Exception:
return False
def _should_autorun() -> bool:
if _is_streamlit_runtime():
return False
if _is_self_rerun():
return False
main = _get_main_path()
if not main:
return False
# run.py 자체를 메인으로 실행한 경우(직접 실행)는 무시
if _is_same_file(main, __file__):
return False
# 정말 Streamlit 앱인지 간단 판별
if not _looks_like_streamlit_app(main):
return False
return True
def _autorun():
env = os.environ.copy()
env["SELF_STREAMLIT"] = "1" # 재귀 방지
subprocess.run([sys.executable, "-m", "streamlit", "run", sys.argv[0]], env=env)
raise SystemExit # 현재 프로세스 종료(이중 실행 방지)
# import 되는 순간 자동 판단/실행 (__name__ 체크 없이 동작)
try:
if _should_autorun():
_autorun()
except SystemExit:
raise
except Exception:
# 어떤 예외가 발생해도 일반 파이썬 실행을 막지 않음
pass
Python
복사