Accessing command line arguments inside a children page in a MPA using session_state

Hi, I am currently working on a multi-page application (MPA) whose home page stores the path to my data directory through a command-line argument using argparse with st.session_state.

I am then using the st.session_state in the children pages to access the path to my data directory and append the folder specific to the children page being displayed.

It behaves as intended in normal use cases but throws an error when trying to access the data_dir attribute from st.session_state when being called from any children page directly without accessing it through the main page (e.g. refreshing the children page, or accessing it via URL).

I understand that this is the expected behavior but I am looking for alternatives to circumvent this issue.

Below are code snippets to reproduce this issue:

home.py

import streamlit as st
from argparse import ArgumentParser

parser = ArgumentParser("Hello World!")
parser.add_argument("-d", "--data-dir", help="Data root directory")

args = parser.parse_args()

if "data_dir" not in st.session_state:
    st.session_state.data_dir = args.data_dir

st.write("Hello World!")

st.page_link("pages/first.py", label="First page")

pages/first.py

import streamlit as st
from pathlib import Path

st.write("First page!")

data_root = Path(st.session_state.data_dir) / "first"

def display(path):
    # actual code doing things
    ...

display(data_root / "image.jpg")

Launching streamlit with CLI arguments:

streamlit run home.py -- -d /path/to/my/data/

Any help is appreciated!

That doesn’t seem to be session-specific, so it doesn’t belong to session state. Probably using a cached function would be the most convenient way to access the CLI arguments.

Thank you, caching the CLI arguments works flawlessly indeed!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.