r/learnpython • • 1h ago

I have no idea what's going on

• Upvotes

I have a cron job that runs a python script locally every 30 minutes. One the of functionalities of the code is to send me an imessage using the mac_imessage send_imessage function when API tokens are low (<50). This code has worked as intended as recent as two days ago.

I noticed that I was getting an imessage every time the cron job ran, even if the low API token condition was not met (I've added print statements that do not appear in my logs). I also slightly changed the contents of the message to be sent, but the message that I receive every 30 minutes is still the old version of the message.

Additionally, I've made other updates to my code, like adding code that creates/saves files locally, and that code seems to successfully run as expected.

So the two abnormalities here that I have questions about.

  1. Why is my low API token check being triggered every time my code is executed, even when the condition is not met?

  2. Why am I receiving imessages with contents that do not match what's in my code?


r/learnpython • • 3h ago

New to python, don't understand this function

6 Upvotes

I'm learning python and I'm stuck on this function because I don't understand why "a" becomes 10 and the result is 5. Is someone able to explain?

def subtract (a, b=5):
    return a - b

print(subtract(10))

r/learnpython • • 9h ago

how do i overwrite a variable?

0 Upvotes
name = "Alice"

def func():
    name = "Bob"

func()

print(f"Hello, {name}!") # i want it to print bob

r/learnpython • • 13h ago

Can't download website html code, web scrapping ,automate the boring stuff with python

0 Upvotes

I'm currently learning webscrapping with automate the boring stuff with python> In one example we use the module requests like this

url = f"https://pypi.org/search/?q={search}"

resp = requests.get(url)

when i print resp.text there are this error message in the html code.

"A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser."

"JavaScript is disabled in your browser"

my browser is chrome I tried using microsoft edge .


r/learnpython • • 3h ago

Python CDP and MCP

0 Upvotes

Melhor maneira de trabalhor com os dois juntos sem barreiras de processamento pelo navegador Brave


r/learnpython • • 11h ago

I am tryoing to take innput from user, but if it is of the wrong data type or doesnt mathc the condition then i want to restart the process of asking input

0 Upvotes

I have put toghether this code but it doesnt work

while c==1:

C_ID=int(input('enter customer id'))

locn(C_ID,8)

Customer_name=input('enter customer name')

locv(Customer_name,40)

Number=int(input('enter contact number'))

locn(Number,10)

Delivery_status=input('enter delivery status')

locv (Delivery_status,10)

value=(C_ID,Customer_name,Number,Delivery_status)

cur.execute('insert into customer values{}'.format(value,))

cur.commit()

if c==0:

c=1

def locv (x,y):

if len(x)>y:

print('the string should not exceed ',y,' characters long' )

c=0

def locn(x,y):

if len(str(x))!=y:

print('the nermber should be',y,' long')

c=0

this program is for creating an sql user interface via python, The conditions for the input has been put into the udf. Now with the current version the code continues even if the input from the user doesnt match the given conditions.

(Please ignore the indentation, in the actual code it is fine but while copying here something happneded to it.

What do i do to restan the process of taking input from the user?

Thanks in advance!


r/learnpython • • 14h ago

Is None as a sentinel the standard fix for mutable default arguments, or are there better options?

7 Upvotes

I’m reading about mutable default arguments in Python. This function shares its list across calls:

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b']

My understanding is that defaults are evaluated once when def runs, so every call without items shares one list. The fix I’ve seen is:

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

Questions:

  1. Is this the idiomatic approach, or is there something better?
  2. For dataclasses, is field(default_factory=list) the right equivalent?
  3. Do linters catch this, and which ones do you use?
  4. Is there a legitimate case for keeping a shared mutable default?

If I’ve misunderstood something, please correct me.


r/learnpython • • 4h ago

My app I need advice

0 Upvotes

#!/usr/bin/env python3

import argparse
import logging
import os
import sys
from pathlib import Path

import maintain

def configure_logging(log_directory: Path) -> None:
log_directory.mkdir(parents=True, exist_ok=True)

from logging.handlers import RotatingFileHandler

file_handler = RotatingFileHandler(
log_directory / "automation.log",
maxBytes=5_000_000,
backupCount=5,
encoding="utf-8",
)

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s UTC %(levelname)s %(message)s",
handlers=[
file_handler,
logging.StreamHandler(sys.stdout),
],
)

# Ensure the timestamps labeled UTC actually use UTC.
import time

logging.Formatter.converter = time.gmtime

def run_maintenance(
app_directory: Path,
public_directory: Path,
) -> int:
config_path = app_directory / "sources.json"
database_path = app_directory / "hustlefinder.sqlite3"

if not config_path.is_file():
logging.error("Missing configuration: %s", config_path)
return 1

public_directory.mkdir(parents=True, exist_ok=True)

# The existing module reads these globals during its operations.
maintain.CONFIG = str(config_path)
maintain.DB = str(database_path)

logging.info("Maintenance started")

try:
configuration = maintain.config()

if not isinstance(configuration.get("sources"), list):
raise ValueError("'sources' must be an array")

if not isinstance(
configuration.get("allowed_link_hosts", []), list
):
raise ValueError("'allowed_link_hosts' must be an array")

with maintain.database():
pass

except Exception:
logging.exception("Configuration or database initialization failed")
return 1

failed = False

# Continue other maintenance even when a feed fails.
try:
failures = maintain.refresh()

if failures:
failed = True
logging.error(
"%d feed refresh(es) failed; inspect the runs table",
failures,
)
else:
logging.info("Feed refresh completed")

except Exception:
failed = True
logging.exception("Feed refresh failed")

try:
maintain.check()
logging.info("Application-link checks completed")

except Exception:
failed = True
logging.exception("Application-link checks failed")

try:
output_path = public_directory / "jobs.json"

# Existing export uses a temporary file followed by replacement.
# Only approved/published records enter the public export.
maintain.export(str(output_path), public=True)

logging.info("Published job data exported to %s", output_path)

except Exception:
failed = True
logging.exception("Public export failed")

logging.info(
"Maintenance finished: %s",
"completed with errors" if failed else "successful",
)

return 1 if failed else 0

def main() -> int:
parser = argparse.ArgumentParser(
description="Run HustleFinder listing maintenance"
)

parser.add_argument(
"--app-dir",
type=Path,
default=Path(__file__).resolve().parent,
)

parser.add_argument(
"--public-dir",
type=Path,
required=True,
)

args = parser.parse_args()

app_directory = args.app_dir.resolve()
public_directory = args.public_dir.resolve()

# Private files should not become publicly served files.
if (
public_directory == app_directory
or public_directory in app_directory.parents
):
parser.error(
"--public-dir must not be the app directory "
"or a parent of the app directory"
)

os.umask(0o027)
configure_logging(app_directory / "logs")

try:
return run_maintenance(app_directory, public_directory)
except Exception:
logging.exception("Unexpected maintenance failure")
return 1

if __name__ == "__main__":
raise SystemExit(main())


r/learnpython • • 9h ago

What's something about being a programmer that you only understood after building real software?

26 Upvotes

​

Hey everyone!

I'm learning Python, and I've been curious about what programming actually feels like once you move beyond learning the basics and start working on real software.

There's a lot of advice online about what to learn, which tools to use, and which projects to build. But I'm more interested in the things you discover through experience that nobody really explains beforehand.

For those of you who've built real applications or worked on software projects:

- What turned out to be much harder than you expected?

- What's something you wish you had understood before building your first serious project?

- Did anything about real-world programming completely change how you think about writing code?

I'm not looking for a perfect roadmap or a list of technologies. I'm genuinely curious about the experiences and lessons that only come from actually building things.

I'm still early in my journey, so hearing different perspectives from people who've been doing this for a while would be really valuable.

Thanks! Looking forward to reading your experiences.


r/learnpython • • 13h ago

keep the multi-process or switch to single process ?

3 Upvotes

hey people

I m developing a program which analyze the file integrity in OS

this program is multi-process and I have used the child processes to hash the files inside the given path and return the result in a shared queue

and now I m thinking about apply other functions like check duplicate , check deleted and others and use the parent process to handle them

which one is better my ideas or keep using the multi-processes approach for the function left?