#๐ Time value not saving to .txt file?
256 messages ยท Page 1 of 1 (latest)
@idle ivy
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.
Oh that's neat dude
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
thanks :)
You mention the code was annotated by ChatGPT - did you write the code yourself?
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
I asked it to remove annotations - here it is if that makes things easier to read: https://paste.pythondiscord.com/JMFA
yo
hey
have you heard of pystyle?
#black-formatter
no
Theres even a vscode extension with witch u only need to select it and press alt+ctrl+f or something like that
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)
what does that do?
this line
details = "jpgame.py",``` is this the file where the timer is located?
Makes ur code look prettyer and more readible
no that's just something I wanted to display on the rpc, I don't believe it does anything in the script
that's the file where the progress is saved
i'll try that
Not much changed it looks like u follow the look standards very good i only said it bc there was some talk on formatters
oh ok, my bad
i guess nobody has an idea of what i could do? i'm kind of running out of ideas lol
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?
You do mean to write to a a new progress.txt every time right?
since you are using mode w I mean
w will set the file pointer to the beginning of the file
not at all, even the cards are saved correctly, this seems to purely be a problem with the time
if this were the problem, then the cards wouldn't save either, right?
the progress.txt is always the same file
honestly I didn't really look at the code, just noticed the open
no new file is created except if it has been deleted
thanks for trying anyway :)
A lot of people mean to use mode w+ but accidentally use w
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
Is the time updated in the txt?
it is not
datetime isn't serializable to json though
U should apply some prints to check if the self total time is updated
Thats why i think pickle is op but u can also just make a timestamp and turn it back at load
hm i'll try that thanks
I'd just define a hook for json_dumps or just turn the date into a string
It looks like self.time is a timestamp already
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
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
really lol?
so total_time is always zero and that elapsed_time grows during one game and then gets throwen away
yeah it appears so
but then why did it work previously?
oh wait maybe it is saved when i put a card in or something?
U exited with the exit command and in the exit sequence u update total time and save it
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
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
Id save the total to the last save the time of the last save and from that we can get at save what the new value should be
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
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
i think you can still do that
if you can run the save command on the program exit then itll work as you described
isn't this what's already being done?
if you x out of the window it will not save but if you exit with command "4" then it should save
i think
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
yeah there is
import atexit
def exit_handler():
print 'My application is ending!'
atexit.register(exit_handler)
use the atexit library
oh that's nice
and just put the saving process into that exit handler function
saving and updating etc
should it be at the end of the code or does it not matter?
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
is putting 'self' there dumb?
you will still need to register that
what does that mean?
you defined the handler function but you didnt do the equivalent of this line
atexit.register(exit_handler)
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
doesn't seem to work for some reason
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
would that be a bad thing?
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
then vscode doesn't like it because the exit_handler is unknown
hmm
i don't get why though
yeah interesting
maybe you can put the registers step outside of the class and do like
game = JapaneseLearningGame()
atexit.register(game.exit_handler)
wait i actually got an error
brb i have to switch a load of laundry but ill return
alright thanks :)
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?
when clicking the cross no, the time doesn't update
the cards always update because when i input them, they're saved automatically
oh the atexit library cant handle this on windows
when refreshing the time does update
oh lol, are there others? i'll check
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
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
looks good to me?
Im unsure what you mean by this, i dont see in your code where the cards are saved.
the only saving i see in your code is when save_progress() is called
oh
doesn't feel right
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
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
i was looking at the wrong self when you brought it up
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
oh rly?
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
hm i get it now
the first argument of a class method is the reference to the instance itself andwe usually just call that instance self
bc the signal_type was darker i thought it was wrong but yeah it just means we're not using it lol
see if that version works
not using it is fine but it is still gonna get sent when the function is called later
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
also i just got what you meant with that and it actually is really funny, i always thought it worked but never implemented it
well
let me try to save time using "4" exit
yeah the "4" exit you mean?
i have no idea
also i still have this error that pops up
when does that error pop up? when you red X out of the console?
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
oh okay
how is that possible? typing 4 doesn't exit the thing
like
?
am i missing something?
it does print the credits
but doesn't exit
or fails to exit maybe because of a library
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
but it doesnt stick open and fails to close?
well it just prints and doesn't do anything
okay weird
i didn't see the window doing smth
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
it still does
i don't get it
i tried to clean up the code
and like potential tests
still doesn't exit
i dont understand it either but if youd like to share the code again i can give it a look over
very weird
yeah maybe comment out the atexit library import cuz i dont see anything that makes sense
hmmm
do you mean the error of it not closing might be because you were spamming enter?
no
the error that popped up for no apparent reason at random intervals
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?
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
okay so the I/O isnt from you its from something else
no, never noticed it before
im looking around at the code for anything that could cause that
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
oh i was worried it was some threading thing cuz i dont have much experience there
so it is solved then?
yeah thats a bad habbit but it definitely happens
i have exams tmrw so i'll prob go to sleep now and try to fix the threading this week-end
okay it sounds like there was at least some progress haha!
thanks a lot for the help, i truly appreciate it
definitely!
of course i was glad to have something to look over, fun project
good luck on exams ๐
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.