Invoking a Python subprocess in a deployed Streamlit app

Let's suppose you want to invoke a subprocess to run a Python script in your deployed Streamlit app For example, the machine learning library Ludwig is run using a command-line interface, or maybe you want to run a bash script or similar type of process from Python.

You have tried the following, but run into dependency issues for, even though you have specified your Python dependencies in a requirements file:

import streamlit as st
import subprocess["python", ""])

When you run the above code block, you will get the version of Python that is on the system path—not necessarily the Python executable installed in the virtual environment that the Streamlit code is running under.

The solution is to detect the Python executable directy with sys.executable:

import streamlit as st
import subprocess
import sys[f"{sys.executable}", ""])

This ensures that is running under the same Python executable as your Streamlit code—where your Python dependencies are installed.

Was this page helpful?

editSuggest edits

Still have questions?

Our forums are full of helpful information and Streamlit experts.