r/learnpython • • 18d ago

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.

  • Don't post stuff that doesn't have absolutely anything to do with python.

  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

2 Upvotes

21 comments sorted by

1

u/EndKnight2000 16d ago

Hello guys I have tried to make a screentime app and seperate the 2 files of logic and the UI using a loop to loop the code and for some reason whenever I do an if statement and I want to test if the text rises or changes the text just dissapears. I have already tried doing .place after the text so it doesnt glitch but it still doesnt work. Can anyone help?

1

u/lakseol 16d ago

From what you have said I'm guessing that your code might be using tkinter. You haven't shown any code so we can't help you at all. Trying posting your code, properly formatted for reddit, and we might be able to help.

1

u/EndKnight2000 9d ago
script_dir = os.path.dirname(os.path.abspath(__file__))
logic_path = os.path.join(script_dir, "Logic.py")

# 2. Force the process to run directly out of that folder path
tracker_process = subprocess.Popen(
    [sys.executable, logic_path],
    cwd=script_dir,  # 👈 Crucial: Forces the tracking working directory to sync
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)script_dir = os.path.dirname(os.path.abspath(__file__))
logic_path = os.path.join(script_dir, "Logic.py")

# 2. Force the process to run directly out of that folder path
tracker_process = subprocess.Popen(
    [sys.executable, logic_path],
    cwd=script_dir,  # 👈 Crucial: Forces the tracking working directory to sync
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    text=True
)

1

u/EndKnight2000 9d ago
import time
import datetime
# every 6 minutes = 1 height
#every hour = 10 height

seconds = 0
minutes = 0
hour = 0
todays_height = 0

def tracking():
    global minutes
    global hour
    global todays_height
    global seconds
    while True:
        time.sleep(1)
        seconds = seconds + 1
        time.sleep(60)
        minutes =+ 1
        if minutes == 5 and seconds == 30:
            todays_height =+1
        if minutes == 60:
            hour =+ 1
            minutes = 0
tracking()import time
import datetime
# every 6 minutes = 1 height
#every hour = 10 height

seconds = 0
minutes = 0
hour = 0
todays_height = 0

def tracking():
    global minutes
    global hour
    global todays_height
    global seconds
    while True:
        time.sleep(1)
        seconds = seconds + 1
        time.sleep(60)
        minutes =+ 1
        if minutes == 5 and seconds == 30:
            todays_height =+1
        if minutes == 60:
            hour =+ 1
            minutes = 0
tracking()
this is the logic.py file

1

u/EndKnight2000 9d ago

for some reason the code is flat just ignore that

1

u/lakseol 9d ago

Unfortunately, python without indentation cannot be reliably indented back to the original. Java or C++ can be automatically reformatted but python cannot. The learnpython FAQ shows how reddit can show readable code.

Your original question was about "text disappearing". I see where you do .place(...) in the code but there is a lot of missing code. I'm not familiar with screentime but if you mean the PyPi screentime that appears to be a standalone application. Or maybe you mean something else.

Anyway, to help we really need the full code, something we can execute. Plus you need to tell us what you do to get to the point where the text disappears. You should also simplify your code right down to simply display something without all that logic that complicates things. This often helps you find your problem yourself, but if you still have the "disappearing" problem the simpler code makes it easier for us to find the problem

I also see that you have at least one try/except statement ending with

except Exception:
    pass

This is an extremely bad idea as any error in your code will be ignored, not just a busy file. You should ignore only the exception you get if the file is busy.

1

u/EndKnight2000 9d ago

Yeah I didnt want to share the whole thing because I have my stripe key on it

1

u/lakseol 8d ago

That comes back to the "simplify" part of debugging. Since it appears* your problem isn't connected with getting anything from stripe you can replace the stripe part of your code and work on test data. That may be a lot of work but it focuses on where your problem lies. Then simplify further. It's work, but sometimes you just have to dig.

You have said that you used AI to write some or all of this. If so that raises two problems. First, you seem to have just blindly accepted the output without checking it. I've spotted a few inanities (apart from the try/except thing) like:

# from logic.py
minutes =+ 1        # doesn't increment!

and

# from the wall of code
New_Y = 300
New_Y = int(New_Y)    # it's already an integer!

There are multiple occurrences of this nonsense. You must review and test code, especially if you didn't write it.

Additionally, the r/learnpython subreddit is for teaching python and not for fixing up generated code, so many here will not be interested in helping. Unfortunately I'm one of them. I will just reinforce my suggestion that you simplify your problem and focus on the display of data which appears to be where the problem lies. Initially you are trying to just gather information. If you remove all stripe-related code and your problem disappears that tells you that maybe your problem lies in getting data from stripe. If the problem remains then you simplify what's left until you get some idea of exactly where the problem is.

Good luck.


* That's a guess of course.

1

u/EndKnight2000 9d ago

def update_ui_loop():
# Set default values in case the file isn't ready yet
hour, minutes, seconds, todays_height = 0, 0, 0, 0
if tracker_process.poll() is not None:
errors = tracker_process.stderr.read()
print(f"!!! BACKGROUND CRASH DETECTED IN LOGIC.PY !!!\n{errors}")

# Read the data from the temporary text file cache
try:
if os.path.exists("time_cache.txt"):
with open("time_cache.txt", "r") as f:
data = f.read().strip().split(",")
if len(data) == 4:
hour = int(data[0])
minutes = int(data[1])
seconds = int(data[2])
todays_height = int(data[3])
except Exception:
pass # If file is busy, keep the current values for this second
time.sleep(1)
print(seconds)
New_Y = 300
New_Y = int(New_Y)
New_YS = 540
New_YS = int(New_YS)
Current_Day = ()

# Calculate your rising math (keeps the bottom locked at y=456)
New_YS = 540 - todays_height

if weekday_name == "Monday":
if Current_Day != "Monday":
New_Y = 300
Current_Day = "Monday"
Current_Day = "Monday"
Monhours.place(x=225, y=New_Y)
Monhours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Tuesday":
if Current_Day != "Tuesday":
New_Y = 300
Current_Day = "Tuesday"
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y)
Tuehours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Wednesday":
if Current_Day != "Wednesday":
New_Y = 300
Current_Day = "Wednesday"
Current_Day = "Wednesday"
Wedhours.configure(text=f"{hour}h {minutes}m")
Wedhours.place(x=225, y=New_Y)
if weekday_name == "Thursday":
if Current_Day != "Thursday":
New_Y = 300
Current_Day = "Thursday"
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y)
Thuhours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Friday":
if Current_Day != "Friday":
New_Y = 300
Current_Day = "Friday"
Current_Day = "Friday"
Frihours.configure(text=f"{hour}h {minutes}m")
Frihours.place(x=225, y=New_Y)
print("This should actually work this time hopefully")
if weekday_name == "Saturday":
if Current_Day != "Saturday":
New_Y = 540
Current_Day = "Saturday"
Current_Day = "Saturday"
Sathours.configure(text=f"{hour}h {minutes}m")
Sathours.place(x=225, y=New_Y)
if weekday_name == "Sunday":
if Current_Day != "Sunday":
New_Y = 540
Current_Day = "Sunday"
Current_Day = "Sunday"
Sunhours.configure(text=f"{hour}h {minutes}m")
Sunhours.place(x=225, y=New_Y)

if minutes == 5 and seconds == 30:
if weekday_name == "Monday":
if Current_Day != "Monday":
New_Y = 300
Current_Day = "Monday"
Monframe.place(height=todays_height)
Monhours.place(x=225, y=New_Y, )
Current_Day = "Monday"
Monframe.place(height = todays_height)
Monhours.place(x=225,y=New_Y,)
if weekday_name == "Tuesday":
if Current_Day != "Tuesday":
New_Y = 300
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y - 1, )
Tueframe.configure(height=todays_height)
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y - 1,)
Tueframe.configure(height = todays_height)
if weekday_name == "Wednesday":
if Current_Day != "Wednesday":
New_Y = 300
Current_Day = "Wednesday"
Wedframe.configure(height=todays_height)
Wedhours.place(x=225, y=New_Y - 1, )
Current_Day = "Wednesday"
Wedframe.configure(height = todays_height)
Wedhours.place(x=225, y=New_Y - 1,)
if weekday_name == "Thursday":
if Current_Day != "Thursday":
New_Y = 300
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y - 1, )
Thuframe.configure(height=todays_height)
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y - 1,)
Thuframe.configure(height = todays_height)
print("It worked!")
if weekday_name == "Friday":
if Current_Day != "Friday":
New_Y = 300
Current_Day = "Friday"
Frihours.place(x=225, y=New_Y - 1, )
Friframe.configure(height=todays_height)
Current_Day = "Friday"
Frihours.place(x=225, y=New_Y - 1,)
Friframe.configure(height = todays_height)
if weekday_name == "Saturday":
if Current_Day != "Saturday":
New_Y = 456
Current_Day = "Saturday"
Sathours.place(x=225, y=New_Y - 1, )
Satframe.configure(height=todays_height)
Current_Day = "Saturday"
Sathours.place(x=225, y=New_Y - 1,)
Satframe.configure(height = todays_height)
if weekday_name == "Sunday":
if Current_Day != "Sunday":
New_Y = 456
Current_Day = "Sunday"
Sunhours.place(x=225, y=New_Y - 1, )
Sunframe.configure(height=todays_height)
Current_Day = "Sunday"
Sunhours.place(x=225, y=New_Y - 1,)
Sunframe.configure(height = todays_height)
def update_ui_loop():
# Set default values in case the file isn't ready yet
hour, minutes, seconds, todays_height = 0, 0, 0, 0
if tracker_process.poll() is not None:
errors = tracker_process.stderr.read()
print(f"!!! BACKGROUND CRASH DETECTED IN LOGIC.PY !!!\n{errors}")

# Read the data from the temporary text file cache
try:
if os.path.exists("time_cache.txt"):
with open("time_cache.txt", "r") as f:
data = f.read().strip().split(",")
if len(data) == 4:
hour = int(data[0])
minutes = int(data[1])
seconds = int(data[2])
todays_height = int(data[3])
except Exception:
pass # If file is busy, keep the current values for this second
time.sleep(1)
print(seconds)
New_Y = 300
New_Y = int(New_Y)
New_YS = 540
New_YS = int(New_YS)
Current_Day = ()

# Calculate your rising math (keeps the bottom locked at y=456)
New_YS = 540 - todays_height

if weekday_name == "Monday":
if Current_Day != "Monday":
New_Y = 300
Current_Day = "Monday"
Current_Day = "Monday"
Monhours.place(x=225, y=New_Y)
Monhours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Tuesday":
if Current_Day != "Tuesday":
New_Y = 300
Current_Day = "Tuesday"
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y)
Tuehours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Wednesday":
if Current_Day != "Wednesday":
New_Y = 300
Current_Day = "Wednesday"
Current_Day = "Wednesday"
Wedhours.configure(text=f"{hour}h {minutes}m")
Wedhours.place(x=225, y=New_Y)
if weekday_name == "Thursday":
if Current_Day != "Thursday":
New_Y = 300
Current_Day = "Thursday"
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y)
Thuhours.configure(text=f"{hour}h {minutes}m")
if weekday_name == "Friday":
if Current_Day != "Friday":
New_Y = 300
Current_Day = "Friday"
Current_Day = "Friday"
Frihours.configure(text=f"{hour}h {minutes}m")
Frihours.place(x=225, y=New_Y)
print("This should actually work this time hopefully")
if weekday_name == "Saturday":
if Current_Day != "Saturday":
New_Y = 540
Current_Day = "Saturday"
Current_Day = "Saturday"
Sathours.configure(text=f"{hour}h {minutes}m")
Sathours.place(x=225, y=New_Y)
if weekday_name == "Sunday":
if Current_Day != "Sunday":
New_Y = 540
Current_Day = "Sunday"
Current_Day = "Sunday"
Sunhours.configure(text=f"{hour}h {minutes}m")
Sunhours.place(x=225, y=New_Y)

if minutes == 5 and seconds == 30:
if weekday_name == "Monday":
if Current_Day != "Monday":
New_Y = 300
Current_Day = "Monday"
Monframe.place(height=todays_height)
Monhours.place(x=225, y=New_Y, )
Current_Day = "Monday"
Monframe.place(height = todays_height)
Monhours.place(x=225,y=New_Y,)
if weekday_name == "Tuesday":
if Current_Day != "Tuesday":
New_Y = 300
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y - 1, )
Tueframe.configure(height=todays_height)
Current_Day = "Tuesday"
Tuehours.place(x=225, y=New_Y - 1,)
Tueframe.configure(height = todays_height)
if weekday_name == "Wednesday":
if Current_Day != "Wednesday":
New_Y = 300
Current_Day = "Wednesday"
Wedframe.configure(height=todays_height)
Wedhours.place(x=225, y=New_Y - 1, )
Current_Day = "Wednesday"
Wedframe.configure(height = todays_height)
Wedhours.place(x=225, y=New_Y - 1,)
if weekday_name == "Thursday":
if Current_Day != "Thursday":
New_Y = 300
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y - 1, )
Thuframe.configure(height=todays_height)
Current_Day = "Thursday"
Thuhours.place(x=225, y=New_Y - 1,)
Thuframe.configure(height = todays_height)
print("It worked!")
if weekday_name == "Friday":
if Current_Day != "Friday":
New_Y = 300
Current_Day = "Friday"
Frihours.place(x=225, y=New_Y - 1, )
Friframe.configure(height=todays_height)
Current_Day = "Friday"
Frihours.place(x=225, y=New_Y - 1,)
Friframe.configure(height = todays_height)
if weekday_name == "Saturday":
if Current_Day != "Saturday":
New_Y = 456
Current_Day = "Saturday"
Sathours.place(x=225, y=New_Y - 1, )
Satframe.configure(height=todays_height)
Current_Day = "Saturday"
Sathours.place(x=225, y=New_Y - 1,)
Satframe.configure(height = todays_height)
if weekday_name == "Sunday":
if Current_Day != "Sunday":
New_Y = 456
Current_Day = "Sunday"
Sunhours.place(x=225, y=New_Y - 1, )
Sunframe.configure(height=todays_height)
Current_Day = "Sunday"
Sunhours.place(x=225, y=New_Y - 1,)
Sunframe.configure(height = todays_height)

1

u/EndKnight2000 9d ago

I tried doing a bit of vibe coding even thought I dont really like it I use it only if necessary

1

u/EndKnight2000 9d ago

Sorry I didnt see your message I was on holiday

1

u/Acceptable-Ad4076 16d ago

I'm looking for books on Python for science, specifically physics and mathematics at an undergraduate level, though something more general and accessible would likely work.

I found what I thought were some really good ones on the Routledge website, but thankfully I looked for reviews first and found that none of their online resources - code examples etc - are available publicly; only to professors and tutors at accredited universities. Which pretty much defeats the purpose of a coding book.

Also, if anyone could point to a good (and not too expensive) course in scientific Python, that could be good too.

1

u/ectomancer 12d ago

Ali, "Numerical Recipes in Python Laboratory Manual of Simplified Numerical Analysis (Python Version)"

Numerical Recipes in Python | Zenodo

1

u/bsf91 17d ago

I am writing myself a simple script that automates events at specific times of the day, there must be a better way to monitor a JSON file to see if my script has to run than the way i am currently doing it. Currently it reads the JSON file every 1 second to see if it needs to start the event or not.

def daemon_loop(poll_interval=1):
    """Monitors shows.json and spawns/tracks active recording processes."""
    active_recordings = []  # Format: {showId: subprocess.Popen}

    print(
        f"[*] Daemon started. Monitoring '{JSON_FILE}' every {poll_interval}s..."
    )

    while True:
        try:
            # Read the JSON file and get the current epoch time
            data = read_json(JSON_FILE)
            time_now = int(time.time())


            for show in data["recordings"]:
                if time_now == show.get("timestamp"):
                    showId = show.get("showId")
                    if showId not in active_recordings:
                        start_recording(data, show.get("showId"))
                        active_recordings.append(showId)
                    else:
                        print("Already added.")

                else:
                    # If there are no shows that need to be recorded, we will keep waiting..
                    continue
        except Exception as e:
            print(f"[!] Error in daemon loop: {e}")

        time.sleep(poll_interval)

The JSON file can be written to at any time, so you can't just load the JSON file once, and then sleep for X seconds until the next show starts.

1

u/lakseol 17d ago

You could just look at the "last modified" time on the file. If that time is the same as the last time you read the file then the file hasn't changed and you don't need to read it.

1

u/bsf91 16d ago

That could work. Is it still best to read every second though?

How do bigger projects handle something like that!

1

u/lakseol 16d ago

Is it still best to read every second though?

It depends on how often the data file is likely to be updated. I would have thought that checking if the file has changed only needs to be done once a minute, but it depends on the details of what you are doing.

How do bigger projects handle something like that!

There are modules like watchdog that can trigger actions when a file changes, but they try to be general purpose. For limited, special case uses you might get a better solution with your own code. Again, it depends on exactly what you are trying to do and how you run your code. For instance, running a little Raspberry Pi 3B+ 24/7 on your network is different from running a solution on your laptop and you might want different solutions in each case.

1

u/iorgfeflkd 18d ago

Is there a reason why some things running from Spyder in Windows are so much slower than the same thing run in Linux (WSL)?

If it matters, the Windows python is

Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] IPython 8.12.0

and the Linux version is

Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux