KeyError: 'st.session_state has no key in Streamlit - python

The Code:
# Libraries
import io
import os
import numpy as np
import pandas as pd
import streamlit as st
def login():
# interface codes for the login screen
# (css,buttons,background,input area etc )
path_input_0 = st.text_input(
"File Path:",
"Please enter the path to the folder containing the Abstract_Account_Web_App.py file",
key="PATH_INPUT_LAST"
)
st.write(path_input_0)
global proceed
if st.button("Proceed"):
st.session_state["page"] = "main"
st.balloons()
st.experimental_rerun()
def main():
if 'PATH_INPUT_LAST' in st.session_state:
file0 = st.session_state["PATH_INPUT_LAST"]+"/Bankomat Alışveriş Özeti.csv"
st.write(file0)
if(os.path.exists(file0) and os.path.isfile(file0)):
os.remove(file0)
print("file was deleted as preprocessing")
else:
print("file was not found to delete")
# interface codes for the main screen
# (css,input,buttons etc.)
def set_texts(pdf_files:list):
print("starting to text process")
#This function reads pdf and gets "CRC-32" components as texts
for pdf_file in pdf_files:
with fitz.open(pdf_file) as doc:
text = ""
for page in doc:
new_text = page.get_text()
text += new_text
return text
pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
st.write("path1:", pathz)
file_names = r'%s' % pathz
st.write(file_names)
set_texts([file_names])
if st.button('Show Info Analysis'):
st.write(file_names) #ERROR HERE
if __name__ == "__main__":
if "page" not in st.session_state:
st.session_state["page"] = "login"
if st.session_state["page"] == "login":
login()
elif st.session_state["page"] == "main":
st.balloons()
main()
Hello friends, I’m entering the input area on the login screen: "folder path containing the Abstract_Account_Web_App.py file" and then I am pressing the Proceed button.
When it comes to the main screen, path1, and file_names are displayed correctly and properly. However, when I click the 'Show Info Analysis' button on the main screen, I get an error as below:
"KeyError: 'st.session_state has no key "PATH_INPUT_LAST". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced -features/session-state#initialization'"
How can I solve this problem?
Traceback:
File "f:\anaconda\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 556, in _run_script
exec(code, module.__dict__)
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 85, in <module>
main()
File "C:\Users\Desktop\abstract_account\Abstract_Account_Web_App.py", line 64, in main
pathz = st.session_state["PATH_INPUT_LAST"] + "/Bankomat Alışveriş Özeti.pdf"
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state_proxy.py", line 93, in __getitem__
return get_session_state()[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\safe_session_state.py", line 111, in __getitem__
return self._state[key]
File "f:\anaconda\lib\site-packages\streamlit\runtime\state\session_state.py", line 440, in __getitem__
raise KeyError(_missing_key_error_message(key))

def login():
# interface codes for the login screen
# (css,buttons,background,input area etc )
path_input_0 = st.text_input(
“File Path:”,
“Please enter the path to the folder containing the Abstract_Account_Web_App.py file”) #delete key
and
if st.button("Proceed"):
st.session_state["page"] = "main"
st.session_state["PATH_INPUT_LAST"] = path_input_0 #add this
st.balloons()
st.experimental_rerun()

Related

can't play mp3 files continuously inside a loop using pygame? [duplicate]

This question already has an answer here:
I've got an error when trying to create sound using pygame
(1 answer)
Closed 2 years ago.
Hi i want to play a mp3 but when the function recalled that is logCreater an error shows can load mp3.
First time it play audio correctly but when it's recalled then it cant load mp3.
error msg say's pygame.mixer.music.load cant load xxxxx.mp3 file
Actually this is lil project and this is just one module of it.
Please suggest me the code correction.
Error message is :
Traceback (most recent call last):
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 151, in
timCount()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\MainModule.py", line 65, in timCount
EyeExcercise.logCreater()
File "e:\Tutorials etc\ProjBack\Healthy_programmer_cli\EyeExcercise.py", line 45, in logCreater
pygame.mixer.music.load("Eyesound.mp3")
pygame.error: Couldn't open 'Eyesound.mp3'
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
from os.path import expanduser
import time as t
import getpass
usernm = getpass.getuser()
from datetime import datetime
import pygame
def userDirFinder():
from os.path import expanduser
usrpth = expanduser("~")
mainp = os.path.join(usrpth, "Documents")
return mainp
def checknSetdir():
mainp=userDirFinder()
target_path = os.path.join(mainp,"HealthManger","Eye_Excercise_log")
if os.path.exists(target_path):
os.chdir(target_path)
else:
os.makedirs(target_path)
os.chdir(target_path)
def getCurrentDateandTime():
Dat = datetime.now()
currentD = Dat.strftime("%d/%m/%Y")
currentT = Dat.strftime("%I:%M %p")
return currentD , currentT
def logCreater():
print("Countdown paused")
pygame.mixer.init()
pygame.mixer.music.load("Eyesound.mp3")
pygame.mixer.music.play(-1)
write_msg = f"Eye Excercise Done by {usernm}"
while 1:
try:
print("Time for a Eye Excercise Break , After the Eye Excercise")
usr_msg = input("Type \"Done\" to stop this alarm: ")
usr_msg = usr_msg.lower()
if usr_msg != "done":
raise ValueError("Invalid Answer")
elif "done" == usr_msg:
checknSetdir()
with open("eye_excercise_log.txt","a") as fi:
cdat , ctim = getCurrentDateandTime()
fi.write(f"Date: {cdat} Time: {ctim} Message: {write_msg}\n")
# print("Log Created")
pygame.mixer.music.stop()
break
except Exception as e:
print(e)
def logReader():
try:
checknSetdir()
with open("eye_excercise_log.txt","r") as fi:
lis = fi.readlines()
for i in lis:
print(i)
input("Press to contiue")
except FileNotFoundError:
print("File is not created Yet")
input("Press to contiue")
if __name__ =="__main__":
while True:
logCreater()
First time it play audio correctly but when it's recalled then it cant load mp3
After playing the music, the current working directory is changed in the function checknSetdir, by os.chdir(target_path).
Get the current working directory at the begin of the application:
import os
currentWorkDir = os.getcwd()
Use an absolut path to load the file "Eyesound.mp3":
pygame.mixer.music.load(os.path.join(currentWorkDir, "Eyesound.mp3"))

class SystemDialog: is not recognizing my system dialog window

I am trying to upload some files to a website and so far I've tried everything I could find and nothing is working. The html input element won't let me sendKeys to it so I found this class to try and use it.
class SystemDialog:
RECURSION_LIMIT = 20
def __init__(self, application_pid, dialog_title=None):
self.__path_to_file = None
self.__recursions = 0
self.dialog_title = "Open" if dialog_title is None else dialog_title
self.accept_button = "&SaveButton" if self.dialog_title == "Save As" else "&OpenButton"
self.decline_button = "&CancelButton"
app = pywinauto.application.Application()
app.connect(process=application_pid)
self.dialog = app.window(title=self.dialog_title)
def __wait_for_dialog(self):
start = time.time()
while not self.dialog.exists() and (time.time() - start) <= 10:
time.sleep(1)
if not self.dialog.exists():
raise Exception("System Dialog did not show in 10 seconds")
def input_file_path(self, path_to_file):
self.__wait_for_dialog()
self.__path_to_file = path_to_file
if path_to_file is not None:
self.dialog.set_focus()
self.dialog.Edit.type_keys(self.__path_to_file)
return self
def accept(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to accept the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.accept_button].click()
if self.dialog.exists():
self.__recursions += 1
if self.__path_to_file is not None:
return self.input_file_path(self.__path_to_file).accept() # <--- FYI Recursion
else:
raise Exception("Trying to accept dialog without any inputs, not gonna work.")
self.__recursions = 0
def decline(self):
if self.__recursions == SystemDialog.RECURSION_LIMIT:
raise Exception("Not able to decline the System dialog.")
self.__wait_for_dialog()
self.dialog.set_focus()
self.dialog[self.decline_button].click()
if self.dialog.exists():
self.__recursions += 1
return self.decline() # <--- Recursion
self.__recursions = 0
Here is the HTML as well
HTML
Here is me trying to send the files in my python code:
#Upload files
click(driver, 5, By.XPATH, '//*[#id="dm-react-shared-container"]/div/div[10]/div/div[1]/div[1]/div[2]/div[1]/div/div/div[5]/div/div[2]/div/div[2]', False)
click(driver, 5, By.XPATH, '//*[#id="downshift-0-label"]/div[1]/button', False)
process = psutil.Process(driver.service.process.pid) # chromedriver pid
pid = process.children()[0].pid # chrome tab pid
dialog = SystemDialog(application_pid=pid)
dialog.input_file_path(path)
dialog.accept()
I am met with this error:
Traceback (most recent call last):
File "blaineus_v2.py", line 331, in <module>
main()
File "blaineus_v2.py", line 64, in main
uploadPDFs(destination, driver, email, password, projectName)
File "blaineus_v2.py", line 324, in uploadPDFs
dialog.input_file_path(path)
File "blaineus_v2.py", line 91, in input_file_path
self.__wait_for_dialog()
File "blaineus_v2.py", line 88, in __wait_for_dialog
raise Exception("System Dialog did not show in 10 seconds")
Exception: System Dialog did not show in 10 seconds

How to run python scripts from path while including extra files like .txt

I am currently working on a script that allows you to type in a path of a python script and run it, this is useful for running the same type of code a lot for troubleshooting because sometimes the program crashes CMD and you have to re-enter all the information of the location ECT.At the moment it works perfectly, however it comes up with the error
Traceback (most recent call last):
File "E:\Coding Type of stuff\Python\Testing\test.py", line 1, in <module>
print(open("text.txt","r").readlines()[0])
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'
I am aware of why this is happening, but is there any fix?
Current code of python script runner:
import tkinter as tk
from subprocess import Popen
try:
path = (open("path.txt","r").readlines())[0]
print(path)
except:
path = "Enter path..."
open("path.txt","w").write("")
def on_entry_click(event):
if entry.get() == path:
entry.delete(0, "end")
entry.insert(0, '')
entry.config(fg = 'black')
def on_focusout(event):
if entry.get() == '':
entry.insert(0, path)
entry.config(fg = 'grey')
def get_input(box):
try:
path = box.get()
if path != "Enter path...":
open("path.txt","w").write(path)
Popen('python "'+path+'"')
else:
print("No path entered")
except:
print("That path does not work")
root = tk.Tk()
root.geometry("375x50")
label = tk.Label(root, text="Path: ")
label.grid(row = 0, column = 0)
entry = tk.Entry(root, bd=1, width = 50)
entry.insert(0, path)
entry.bind('<FocusIn>', on_entry_click)
entry.bind('<FocusOut>', on_focusout)
entry.config(fg = 'grey')
button = tk.Button(root, text = "Run", command = lambda: get_input(entry))
entry.grid(row = 0, column = 1)
button.grid(row = 1)
root.mainloop()
You could check if the file exists first using:
import os
path_exists = os.path.isdir("###your_dir###")
file_exists = os.path.exists("text.txt")

How can I import an input from one file to another and synchronize it?

I want to synchronize my input in one file with the variables in another file. Where should I put my return statement in the login function in order to import variables to another file and synchronize there?
I have tried to put return username, password inside the login function and import that login function in other file and get the variables
class main:
def __init__(self, master):
# Window
self.master = master
# Some Usefull variables
self.username = StringVar()
self.password = StringVar()
self.n_username = StringVar()
self.n_password = StringVar()
# Create Widgets
self.widgets()
# Login Function
def login(self):
# Establish Connection
with sqlite3.connect('quitq.db') as db:
c = db.cursor()
return self.username, self.password ### this one I added to try to send other file
# Find user If there is any take proper action
find_user = ('SELECT * FROM user WHERE username = ? and password = ?')
c.execute(find_user, [(self.username.get()), (self.password.get())])
result = c.fetchall()
if result:
self.logf.pack_forget()
self.head['text'] = self.username.get() + '\n Loged In'
self.head['pady'] = 150
top1.deiconify()
else:
ms.showerror('Oops!', 'Username Not Found.')
This is the main file where I tried to use return statement in order to use in the following code:
import datetime
import email
import imaplib
import menu
username, password = menu.main.login()
a = username
b = password
EMAIL_ACCOUNT = a
PASSWORD = b
I'm getting this error:
Traceback (most recent call last):
File "C:code/menu.py", line 4, in <module>
import email_client
File "C:\code\email_client.py", line 4, in <module>
import menu
File "C:\code\menu.py", line 285, in <module>
email_from, email_to, local_message_date, subject, body = email_client.get_email()
AttributeError: module 'email_client' has no attribute 'get_email'

Python unitesting Html-test runner index out of range

Hi guys I'm new to automation and trying out to automate my ui and generate the HTML test report for it. I'm using Html-test runner for it.
Please refer the following code:
#invalid Password
def test1(self):
rva = signUp_invalidpassword(self.driver)
self.assertEqual("Error : Invalid password",rva)
time.sleep(6)
# self.driver.refresh()
# time.sleep(10)
#Password Mismatch
def test2(self):
rvb = signUp_passwordmismatch(self.driver)
self.assertEqual("Error : Confirm Password is not matching",rvb)
time.sleep(5)
#Signup Succesfully
def test3(self):
time.sleep(5)
rvc = signUp(self.driver)
self.assertEqual("Device Monitoring and Analysis Tool",rvc)
time.sleep(8)
#Default RF parameter
def test4(self):
rvd = SignIn(self.driver)
self.assertEqual("RSRP",rvd)
time.sleep(5)
#Default Zoom_level
def test5(self):
rve = zoomLevel(self.driver)
self.assertEqual("Zoom level: 4.0",rve)
time.sleep(5)
#Chance RF parameter
def test6(self):
rvf = changeRF(self.driver)
self.assertEqual("RSRQ",rvf)
time.sleep(4)
#Empty Search State
def test7(self):
rvg = noState(self.driver)
self.assertEqual("Please enter a search term.",rvg)
time.sleep(4)
#Polygon Functionality
def test8(self):
rvj = polygon(self.driver)
self.assertEqual("CLOSE",rvj)
if __name__=='__main__':
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='Dmat_dir'))
But I'm getting the following output:
Generating HTML reports...
Traceback (most recent call last):
File "C:/Users/inswadhwa/PycharmProjects/automation/assertion.py", line 99, in <module>
unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='Dmat_dir'))
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\unittest\main.py", line 95, in __init__
self.runTests()
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\unittest\main.py", line 256, in runTests
self.result = testRunner.run(self.test)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\runner.py", line 95, in run
result.generate_reports(self)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 339, in generate_reports
testRunner)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 316, in _report_tests
tests = self.sort_test_list(tests)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 303, in sort_test_list
return sorted(test_list, key=self.get_test_number)
File "C:\Users\inswadhwa\AppData\Local\Programs\Python\Python36-32\lib\site-packages\HtmlTestRunner\result.py", line 295, in get_test_number
test_number = int(test_name.split('_')[1])
IndexError: list index out of range
Process finished with exit code 1
Can any one help me with this?
Try changing the name from test1 to test_1 for all test. From the error it seems the runner assumes there will be _ in the name
To control the order use test names like test_001, test_002 and so on.
Also it seems HtmlTestRunner is quite basic and not a great option. So look for alternatives

Categories

Resources