How do I access the arguments passed the script itself?

According to the CLI documentation, https://docs.streamlit.io/en/latest/cli.html, you can pass arguments to the script that will be run. Inside that script, how do we access those arguments? Could we do the same thing we usually do with argparse to access them (I know about the – vs - caveat)?

Hi @Jane_Wayne, welcome to the Streamlit community!

From my brief look at https://github.com/streamlit/streamlit/blob/develop/lib/streamlit/cli.py, it looks like we consume these arguments directly, rather than store them as variables. What sort of use case are you imagining?

Best,
Randy

I tinkered a bit and it seems the arguments after – all can be consumed and processed with argparse like any plain old python script. The only β€œuse case” we have are passing in β€œhints” to the script to react as appropriate (e.g. sample a dataframe instead of using the data entirely).

1 Like

Hey @Jane_Wayne,

Glad you worked out something :slight_smile: are you able to post a small code snippet for people who may face a similar situation later on ?

Fanilo

1 Like

Here’s a snippet.

import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import argparse
import sys
import missingno as msno


def parse_args(args):
    parser = argparse.ArgumentParser('Data Diagnostics')
    parser.add_argument('-f', '--file', help='CSV file', required=True)
    parser.add_argument('--seed', help='Seed for random generator', default=37, required=False)
    return parser.parse_args(args)


@st.cache
def get_data(fpath):
    return pd.read_csv(fpath)


args = parse_args(sys.argv[1:])
np.random.seed(args.seed)
plt.style.use('ggplot')
2 Likes