#๐Ÿ”’ Time value not saving to .txt file?

256 messages ยท Page 1 of 1 (latest)

ebon trailBOT
#

@idle ivy

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

idle ivy
#

Screenshot of the interface:

tawny field
#

Oh that's neat dude

idle ivy
#

Hey everyone! I'm having trouble with the time value not being saved.

It is supposed to save in a .txt file, fairly simple, using this:

 def save_progress(self):  # Method to save player's progress to a file
        # Creating a dictionary containing player's progress data
        data = {
            'progress': self.progress,
            'level': self.level,
            'xp': self.xp,
            'badges': self.badges,
            'streak': self.streak,
            'currency': self.currency,
            'total_cards': self.total_cards,
            'total_time': self.total_time
        }
        with open('progress.txt', 'w') as file:  # Opening the progress file in write mode
            json.dump(data, file)  # Writing data to the file in JSON format

(code annotated by chat-gpt)

However, I find it stopped working after I added Discord RPC to the mix.

Here's the RPC:

def richpresence():
    client_id = "1235640528364900452"  # Rich Presence client ID
    RPC = Presence(client_id)
    RPC.connect()
    RPC.update(
                    

                details = "jpgame.py",
                start = int(time.time()),
                large_image = "1",
                large_text = "JLG"
                    
                )

I believe maybe it has to do with the fact that I use the same library to save the time, but I have no idea how to fix it lol. Any idea? I tried debugging but there isn't even an error to start with

idle ivy
tawny field
#

You mention the code was annotated by ChatGPT - did you write the code yourself?

idle ivy
#

yes I did, but I asked ChatGPT to annotate it for me so my friend could read it better

#

he tried to help me previously but we didn't succeed

orchid halo
#

yo

idle ivy
#

hey

orchid halo
#

have you heard of pystyle?

inner spoke
#

#black-formatter

idle ivy
#

no

inner spoke
orchid halo
#

what's the output?

idle ivy
#

the output works normally

#

except when i close the app and restart it again, the total time has been reset

#

it wasn't saved or loaded from the .txt file

#

judging by the state of the .txt, i concluded it wasn't saved (total_time)

orchid halo
#
 details = "jpgame.py",``` is this the file where the timer is located?
inner spoke
idle ivy
#

that's the file where the progress is saved

idle ivy
inner spoke
idle ivy
#

i guess nobody has an idea of what i could do? i'm kind of running out of ideas lol

inner spoke
#

Everything seems to be fine only thing i see is where do u update the presence and in the json u see anything hinting it isn't saved?

tawny field
#

since you are using mode w I mean

#

w will set the file pointer to the beginning of the file

idle ivy
idle ivy
#

the progress.txt is always the same file

tawny field
#

honestly I didn't really look at the code, just noticed the open

idle ivy
#

no new file is created except if it has been deleted

idle ivy
tawny field
#

A lot of people mean to use mode w+ but accidentally use w

idle ivy
#

yeah lol i myself made the mistake to use the wrong letters for a long time before realizing why my program didn't work properly

inner spoke
idle ivy
#

it is not

tawny field
#

datetime isn't serializable to json though

inner spoke
#

U should apply some prints to check if the self total time is updated

inner spoke
tawny field
#

I'd just define a hook for json_dumps or just turn the date into a string

inner spoke
#

1 total time only updates on exit but is saved at save 2 with pickle its unreadable but u could dump the whole game instance

timber frost
# idle ivy this line

when you are looking at this printed line that is labeled "tota ltime spent" you are not actually looking at the total_time variable, you are looking at elapsed_time

#

elapsed_time = int(time.time() - self.start_time) + self.total_time this line feeds that print

#

so the fact that the printed label reads "total" but the actual variable elapsed_time is whats messing with you

#

you also never save elapsed_time you just use it to print and then throw it away

idle ivy
#

really lol?

timber frost
#

so total_time is always zero and that elapsed_time grows during one game and then gets throwen away

#

yeah it appears so

idle ivy
#

but then why did it work previously?

#

oh wait maybe it is saved when i put a card in or something?

inner spoke
idle ivy
#

honestly, is there a simpler way of tracking a total time? maybe like saving the time every 5s or something? i feel like my way is inefficient as hell

timber frost
#

i think its okay to just calculate the time only when you are ready to use it.

#

no need to update itevery five seconds if its not going to be used every five seconds

inner spoke
timber frost
# inner spoke U exited with the exit command and in the exit sequence u update total time and ...

yes, this exit command "4" is the only time the total_time is actually adjusted:

elif choice == "4":  # Handling program exit
                # Printing program credits and exiting

                print("Program Credits: Misudashi. Help for programming : Aidyn.")
                self.total_time += int(
                    time.time() - self.start_time
                )  # Calculating total time spent
                self.save_progress()  # Saving progress before exit
                sys.exit()  # Exiting the program

idle ivy
# timber frost no need to update itevery five seconds if its not going to be used every five se...

in Japanese I typically do a lot of immersion, and so I'm mining sentences for my Anki deck while watching a YT video. In that case, I'm not actually using the program, but still want to track how many hours I've spent on it because it equates to how many hours I've spent learning the language. As soon as I stop immersing I just close the app, and when I start again I open it again with a .bat

#

that system sounded kinda nice but i never could make it work because i can't save total time for now lol

timber frost
#

i think you can still do that

#

if you can run the save command on the program exit then itll work as you described

idle ivy
timber frost
#

if you x out of the window it will not save but if you exit with command "4" then it should save

#

i think

idle ivy
#

is there a way to detect if a terminal is killed using the top right red arrow? i feel like it would be perfect then because having to manually type 4 gets old quick

timber frost
#

yeah there is

#
import atexit

def exit_handler():
    print 'My application is ending!'

atexit.register(exit_handler)
#

use the atexit library

idle ivy
#

oh that's nice

timber frost
#

and just put the saving process into that exit handler function

#

saving and updating etc

idle ivy
#

should it be at the end of the code or does it not matter?

timber frost
#

basically make the atexit callback fuinction do the same thing as "4"

#

it shouldnt matter as long as those lines run

#

when you register the handler itll be ready for you even if more code runs in later lines

#

i havent used it myself but it seems straightforward so if it doesnt work then we can look into it more

idle ivy
#

is putting 'self' there dumb?

timber frost
#

you will still need to register that

idle ivy
#

what does that mean?

timber frost
#

you defined the handler function but you didnt do the equivalent of this line
atexit.register(exit_handler)

idle ivy
#

like this?

#

or should i put it outside the class

timber frost
#

i think that will work as you have it

#

you might want to move the registering part to the init of that class

#

if it doesnt work

#

i think its good though

idle ivy
timber frost
#

oh actually i just realized that if you run the "4" command and then you also X out of the window then it will run those saving things twice

#

hmm

timber frost
#

you should be checking the save file to see if its updated or not that will be a much easier way to bugfix this

#

forexample maybe the exithandler isfailing but also maybe the save function is failing and we dont know which yet

idle ivy
timber frost
#

self.exit_handler i think

#

cuz you made it part of the class

idle ivy
timber frost
#

hmm

idle ivy
#

i don't get why though

timber frost
#

yeah interesting

#

maybe you can put the registers step outside of the class and do like

game = JapaneseLearningGame()
atexit.register(game.exit_handler)
idle ivy
#

wait i actually got an error

timber frost
#

brb i have to switch a load of laundry but ill return

idle ivy
timber frost
#

okay hmmmm

#

ill look up that error with the atexit library maybe it wont work how we wanted

#

dang its unclear to me

#

if you check the json file does it get updated ever?

#

time or otherwise?

idle ivy
#

when clicking the cross no, the time doesn't update

#

the cards always update because when i input them, they're saved automatically

timber frost
#

oh the atexit library cant handle this on windows

idle ivy
#

when refreshing the time does update

idle ivy
timber frost
#

pywin32 can do it

#

this will work the same way that we expected the atexit library to work, except using the pywin32 libary

def on_exit(signal_type):
   print('caught signal:', str(signal_type))

import win32api
win32api.SetConsoleCtrlHandler(on_exit, True)
#

i think that can catch the X button when you close the window

idle ivy
#

hm

#

should i put the import w/ the others?

#

or in the middle of the code

timber frost
#

its usually best to have the imports at the top

#

i just copied that from a stackoverflow google search

#

as long as you import the library before you reference a function from it, then itll work but its best practice to put the imports at the top of the file

idle ivy
#

alright

#

i'm pretty sure that's dumb right?

#

especially the 'self' thing i guess?

timber frost
#

looks good to me?

timber frost
#

the only saving i see in your code is when save_progress() is called

idle ivy
#

save_progress is called when i enter a card number

timber frost
#

oh

idle ivy
#

doesn't work anyway but idk

#

i just yeeted the code and replaced signal_type for self because it didn't know self and i need it for the time

timber frost
#

oh yeah now i see wha you mean

#

yes you need that signal type argument there

idle ivy
#

it felt cheap, just hiding the problem and acting like it doesn't exist, i don't really know how to solve the self thing

timber frost
#

i was looking at the wrong self when you brought it up

idle ivy
timber frost
#

if it is inside the class then you will need both self and signal_type

#

the arent even going to use the signal_type argument but it will still get sent to that function so you have to absorb it

idle ivy
#

oh rly?

timber frost
#

yeah its how callback functions work, whatever exit signal is sent if going to be sent to that exit handler, your exit handler is allowed to just throw it away though so you dont have to use it

idle ivy
timber frost
#

other way around

#

self has to be fisrt if its in the class

timber frost
#

the first argument of a class method is the reference to the instance itself andwe usually just call that instance self

idle ivy
#

bc the signal_type was darker i thought it was wrong but yeah it just means we're not using it lol

timber frost
#

see if that version works

#

not using it is fine but it is still gonna get sent when the function is called later

idle ivy
#

doesn't do anything

#

2182 seconds in the .txt still

timber frost
#

okay i think we are debugging two separate things at once, one if the time problem and one is the exit handling problem

#

and we wont know if we fixed the exit handling until we are sure the time problem is fixed

#

so we cant do both at the same time

idle ivy
#

well

#

let me try to save time using "4" exit

timber frost
#

yeah the "4" exit you mean?

idle ivy
#

the time does indeed save

#

it just is a problem of red cross

#

i'm so dumb

timber frost
#

oh thats good news

#

do you know what the issue was?

idle ivy
#

also i still have this error that pops up

timber frost
#

when does that error pop up? when you red X out of the console?

idle ivy
#

firstly the program didn't exit when i typed 4, but the error wasn't there either, and now i just checked the program and the error popped up seemingly out of nowhere

timber frost
#

oh okay

idle ivy
#

like

#

?

#

am i missing something?

#

it does print the credits

#

but doesn't exit

#

or fails to exit maybe because of a library

timber frost
#

yeah maybe the exit handler is eating up the exit() call lol

#

put a message in your exit handler so you can see when it runs

#

like just a print that shows you that it ran

idle ivy
#

doesn't print it

timber frost
#

but it doesnt stick open and fails to close?

idle ivy
#

well it just prints and doesn't do anything

timber frost
#

okay weird

idle ivy
#

i didn't see the window doing smth

timber frost
#

i would assume your exit handler is making that fail to close

#

you can comment it out and see if it still behaves the same

idle ivy
#

it still does

#

i don't get it

#

i tried to clean up the code

#

and like potential tests

#

still doesn't exit

timber frost
#

i dont understand it either but if youd like to share the code again i can give it a look over

idle ivy
#

result:

timber frost
#

very weird

#

yeah maybe comment out the atexit library import cuz i dont see anything that makes sense

idle ivy
#

still nothing

#

actually the error might just be me

#

spamming enter

timber frost
#

hmmm

#

do you mean the error of it not closing might be because you were spamming enter?

idle ivy
#

no

idle ivy
timber frost
#

oh i see

#

so we dont care about th I/O error cuz that might have been from you, but we do care about the fact that exit() is not closing the window?

idle ivy
#

yes

#

didn't hit enter there

timber frost
#

and that never happened before right? it made sense to me that it could be from all the exit handling stuff but i really dont know

idle ivy
#

program "closed"

#

but just crashed

timber frost
#

okay so the I/O isnt from you its from something else

timber frost
#

im looking around at the code for anything that could cause that

idle ivy
#

ok

#

so

#

it did exit without any problem

#

the thing was the discord rpc for some reason

#

i commented it and it works now i guess

timber frost
#

oh i was worried it was some threading thing cuz i dont have much experience there

#

so it is solved then?

idle ivy
#

yeah prob the threading

#

i guess lol

#

half the code is comments lmao

timber frost
#

yeah thats a bad habbit but it definitely happens

idle ivy
#

i have exams tmrw so i'll prob go to sleep now and try to fix the threading this week-end

timber frost
#

okay it sounds like there was at least some progress haha!

idle ivy
#

thanks a lot for the help, i truly appreciate it

timber frost
#

of course i was glad to have something to look over, fun project

#

good luck on exams ๐Ÿ‘

idle ivy
#

thanks :)

#

have a good one

ebon trailBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.