Stop script when there is error

Hello All,

I have two questions which I will create two post separately.

  1. When there is an error or expected exit, what can be used to exit the script.
    As I see exit(). sys.exit() are not useful in streamlit.

I tried something from: https://gist.githubusercontent.com/treuille/bc4eacbb00bfc846b73eec2984869645/raw/734a2522d68920dfd1c875f321df67b3168afbf5/confirm_button_hack.py

class StopExecution(Exception):
“”“Special Exception which does not display any output to the Streamlit app.”""
pass

try:
	fl= open(textfile,'r', encoding = "utf-8")
except StopExecution:
	st.write (' text file doesnot exist.. exiting')
	pass


if 'string' in open(textfile).read():
		st.write ("")
else:
	st.write ('file is empty.. exiting')
       raise StopExecution

Tried several pattern but I was not successful. Anyone can please suggest if this is correct or am I missing something.

I have also tried

st.stop()

&

raise st.ScriptRunner.StopException

None of them works for me.
Any suggestion would be appreciated.

streamlit --version
Streamlit, version 0.62.1

Hi @7adityaraj, welcome to the Streamlit community!

For a web app, you generally don’t want to stop the app. What use case are you imagining?

Best,
Randy

Hi @randyzwitch,

Thank you for the comment.

I am a beginner here and was trying to run mytest python script via web.

The script usually take a zip file as input and then unzips it and look for specific text file (mytest.txt) and then parse the string that it matches and prints out.

So in the script for below two cases I am willing to get error message and exit the script.

  1. When text file doesn’t exist.
  2. When text file is blank.

This works from python:

> 	try:
> 		fl= open(textfile,'r', encoding = "utf-8")
> 	except:
> 		print ('Text file doesnot exist.. exiting')
> 		exit ()


> 	if 'string1' in open(textfile).read():
>       print ("")
> 	else:
> 		print ('Text file is empty.. exiting')
> 		exit ()
> so on.....

I apologise in advance if provided informations are not clear.

I have found a way… thank you.

1 Like

So whats that? I am experiencing the same problem!