r/learnpython • • 2d ago

Ask Anything Monday - Weekly Thread

3 Upvotes

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.


r/learnpython • • 2h ago

Tips for someone new to Python

3 Upvotes

I’m a brand new python user. Very experienced using R. I will be using python for LCA modeling via the brightway tool. For a python newbie, please drop any tips, tricks, learning guides. Ideally I need to get myself up to speed pretty quickly. Thank you in advance!


r/learnpython • • 9h ago

Calling a Script that uses argparse?

7 Upvotes

I wrote a little Python script that reads in a text file that contains a list of fully qualified files, and checks to see if they exist. I originally wrote it using the argparse module. It was set up to take a filename and a switch, so the command looked like:

"Python dplcheck.py --plname "testing.lst” --showexist y"

This worked fine for a single file, but I wanted to run it for every one of hundreds of list files in a directory, so I wrote another script that generates a list of the .lst files in a directory and calls the first script for each one. But I could not get the second script to pass the arguments in the call to the first script. I tried subprocess.run and subprocess.call, with many different syntaxes and quotes, etc. I ended up removing the use of argparse and just using sys.argv[n] -- which I don't particularly like, since it has no defaults or error handling, etc.

Does anyone know how/if I can call a Python script from another Python script and pass the arguments when the called script uses argparse?


r/learnpython • • 59m ago

Resources for using APIs for sports stats

• Upvotes

This is just for a personal/fun project--I want to learn how to use APIs because I want to play with sports stats (for the NHL/PWHL/international cricket plus a couple of less famous sports leagues like the SDHL). There's an overwhelming number of resources out there and I'm not sure where to start, so any tutorials/suggestions would be welcome. I know there are sport-specific API scrapers that simplify things but I'd like to learn how to do this more generally instead of having to learn a tool for every league.

I mostly program in Matlab but I do use Python sometimes, usually Jupyter notebooks. My coding knowledge is super patchy, I basically know a lot about my projects (data analysis for my research, with the data in specific formats), but very little about anything else.

(Yes, I could use AI, but for a project that's just for my own enjoyment I kinda just want to learn how to do it myself.)


r/learnpython • • 2h ago

I tried to install pygame throught tonny's package manager, and it gave me this error message. Anything I can do to solve this?

1 Upvotes

install --progress-bar off --user pygame

Collecting pygame

Using cached pygame-2.6.1.tar.gz (14.8 MB)

Installing build dependencies: started

Installing build dependencies: finished with status 'done'

Getting requirements to build wheel: started

Getting requirements to build wheel: finished with status 'error'

error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.

│ exit code: 1

╰─> [123 lines of output]

Skipping Cython compilation

WARNING, No "Setup" File Exists, Running "buildconfig/config.py"

Using WINDOWS configuration...

Making dir :prebuilt_downloads:

Downloading... https://www.libsdl.org/release/SDL2-devel-2.28.4-VC.zip 25ef9d201ce3fd5f976c37dddedac36bd173975c

Unzipping :prebuilt_downloads\SDL2-devel-2.28.4-VC.zip:

Downloading... https://www.libsdl.org/projects/SDL_image/release/SDL2_image-devel-2.0.5-VC.zip 137f86474691f4e12e76e07d58d5920c8d844d5b

Unzipping :prebuilt_downloads\SDL2_image-devel-2.0.5-VC.zip:

Downloading... https://github.com/libsdl-org/SDL_ttf/releases/download/release-2.20.1/SDL2_ttf-devel-2.20.1-VC.zip 371606aceba450384428fd2852f73d2f6290b136

---

For help with compilation see:

https://www.pygame.org/wiki/CompileWindows

To contribute to pygame development see:

https://www.pygame.org/contribute.html

---

Traceback (most recent call last):

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1321, in do_open

h.request(req.get_method(), req.selector, req.data, headers,

~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

encode_chunked=req.has_header('Transfer-encoding'))

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1358, in request

self._send_request(method, url, body, headers, encode_chunked)

~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1404, in _send_request

self.endheaders(body, encode_chunked=encode_chunked)

~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1353, in endheaders

self._send_output(message_body, encode_chunked=encode_chunked)

~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1113, in _send_output

self.send(msg)

~~~~~~~~~^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1057, in send

self.connect()

~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\http\client.py", line 1499, in connect

self.sock = self._context.wrap_socket(self.sock,

~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^

server_hostname=server_hostname)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 455, in wrap_socket

return self.sslsocket_class._create(

~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

sock=sock,

^^^^^^^^^^

...<5 lines>...

session=session

^^^^^^^^^^^^^^^

)

^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 1076, in _create

self.do_handshake()

~~~~~~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\ssl.py", line 1372, in do_handshake

self._sslobj.do_handshake()

~~~~~~~~~~~~~~~~~~~~~~~~~^^

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1081)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 389, in <module>

main()

~~~~^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 373, in main

json_out["return_val"] = hook(**hook_input["kwargs"])

~~~~^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\site-packages\pip_vendor\pyproject_hooks_in_process_in_process.py", line 143, in get_requires_for_build_wheel

return hook(config_settings)

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 333, in get_requires_for_build_wheel

return self._get_build_requires(config_settings, requirements=[])

~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 301, in _get_build_requires

self.run_setup()

~~~~~~~~~~~~~~^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 520, in run_setup

super().run_setup(setup_script=setup_script)

~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-build-env-kanljdzv\overlay\Lib\site-packages\setuptools\build_meta.py", line 317, in run_setup

exec(code, locals()) # noqa: S102 # exec is intentional here

~~~~^^^^^^^^^^^^^^^^

File "<string>", line 432, in <module>

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\config.py", line 234, in main

deps = CFG.main(**kwds, auto_config=auto)

File "C:\Users\ASUS\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\config_win.py", line 479, in main

and download_win_prebuilt.ask(**download_kwargs):

~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 265, in ask

update(x86=x86, x64=x64)

~~~~~~^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 248, in update

download_prebuilts(download_dir, x86=x86, x64=x64)

~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 116, in download_prebuilts

download_sha1_unzip(url, checksum, temp_dir, 1)

~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Temp\pip-install-taytx0sx\pygame_236d8736d07842b1bbb489950052c45c\buildconfig\download_win_prebuilt.py", line 51, in download_sha1_unzip

response = urllib.urlopen(request).read()

~~~~~~~~~~~~~~^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 187, in urlopen

return opener.open(url, data, timeout)

~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 487, in open

response = self._open(req, data)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 504, in _open

result = self._call_chain(self.handle_open, protocol, protocol +

'_open', req)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 464, in _call_chain

result = func(*args)

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1369, in https_open

return self.do_open(http.client.HTTPSConnection, req,

~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

context=self._context)

^^^^^^^^^^^^^^^^^^^^^^

File "C:\Users\pcname\AppData\Local\Programs\Thonny\Lib\urllib\request.py", line 1324, in do_open

raise URLError(err)

urllib.error.URLError: <urlopen error \[SSL: CERTIFICATE_VERIFY_FAILED\] certificate verify failed: unable to get local issuer certificate (_ssl.c:1081)>

[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.

ERROR: Failed to build 'pygame' when getting requirements to build wheel

Process returned with code 1

(note, any instance of 'pcname' is the name of my computer, I just needed to keep that private).


r/learnpython • • 8h ago

Needed help

2 Upvotes

Hi! Everyone, I am new to python and I want to learn it fully and clearly and want to make my fundamentals strong. Is there any specific video or website to learn basics and how many months does it usually takes to learn the python completely?


r/learnpython • • 21h ago

Error: failed building wheel for pillow

8 Upvotes

I'm trying to install marker-pdf and then hit with an error,

note: This error originates from a subprocess, and is likely not a problem with pip.

ERROR: Failed building wheel for pillow

Failed to build pillow

error: failed-wheel-build-for-install

× Failed to build installable wheels for some pyproject.toml based projects

╰─> pillow

I've tried to upgrade pip, reinstalling setuptools, wheel, pillow, and none works, the error remains. What should I do?

OS: Arch Linux
Python: 3.14


r/learnpython • • 1d ago

Best way to learn Python for someone not in CS?

15 Upvotes

Hello, so I'm not a CS major. I'm taking a "Bioinformatics" course that is required but turns out it's literally learning and coding Python. CS doesn't come naturally to me. Unfortunately, I think its crazy boring. I'm actually a Biochem major. Even though it's super insanely boring to me, I really want to get a good grade. But I don't know how. My class is equivalent to a professor reading off the slides, but with coding.

What are some recommended resources for beginner python? Like where I could practice a ton. Practice identifying data types, fixing bugs, understanding and explaining why a code will or wont work etc etc. I'm very willing to spend hours on this.


r/learnpython • • 9h ago

My bot started as one Python file and now it's a mess — how did you learn to split a project into modules without breaking everything?

0 Upvotes

I'm a second-year BCA student in Jaipur, learning Python alongside my coursework, and I built a small Telegram bot for myself that started out as one simple file. At first it just did one job, so a single file made sense. Then I kept adding features one at a time — a few more commands, some scheduled messages, a bit of stored data — and now it's a few hundred lines in one file and I'm honestly scared to touch it.

Every change feels risky because everything is tangled together. Functions call each other across unrelated features, I've got similar code copied in two places, and I'm never quite sure what will break if I move something. I've read about modules and packages, but most tutorials use tiny toy examples, and they don't show what the messy middle step looks like on a real, growing project.

So for people who've actually done this refactor: how did you decide where to split? By feature, by layer (commands vs data vs helpers), or something else? Did you move one piece at a time, or rewrite the structure in one go? And without a proper test suite, how did you check after each move that you hadn't broken something quietly?

I'm not looking for the textbook definition of a module — I want to know what your first real split looked like, and what mistake you'd avoid if you did it again.


r/learnpython • • 1d ago

How to properly break out of an infinite loop inside a multiprocessing child process in Python?

4 Upvotes

I am writing a Python script using the multiprocessing module to launch an external application (Notepad) in a continuous loop. However, I want the loop to stop when a specific condition is met or when a key is pressed.

import os
from multiprocessing import Process 
import time
import keyboard

pid = os.getpid()
print(pid)

callable(os.getpid)
path = r"C:\Windows\System32\notepad.exe"

def process_start(path):
    try:
        while True:
            os.system(path)
    except:
        pass

if __name__ == '__main__':
    # Note: Currently calling the function directly instead of passing the reference
    p = Process(target=process_start(path))
    time.sleep(3)
    p.start()

    if keyboard.press_and_release("q") == "q":
        p.terminate()

r/learnpython • • 1d ago

I am looking for a Python learning buddy.

27 Upvotes

I tried learning Python and gave up couple of times. Learning alone is difficult for me. If anybody else feel same then please reachout to me.


r/learnpython • • 1d ago

Is Mimo + Codewars sufficient for learning python?

0 Upvotes

Most stuff like the University of Helsinki courses take 18+ months sooo I wanted to know can I learn python if I do Mimo & after a few beginner chapters I start doing codewars for them would I be able to grasp the same content & knowledge?


r/learnpython • • 21h ago

For each character in name, print character

0 Upvotes

I am totally new to coding and working slowly through the course at futurecoder.io .

On the topic 'Introducing For Loops' we are asked to run the program:

name = 'World'
for character in name: print(character)

I figured character might be some kind of term that python recognises and knows what to do with, like print. Colour me surprised when replacing character with kitten runs, and has the same output. I thought maybe number in place of character might not work, since the characters are all letters, but it works too.

Why is it so? What concept do I need to grasp here?


r/learnpython • • 1d ago

New to python, don't understand this function

26 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 • • 2d ago

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

49 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 • • 1d ago

Why Does Python Provide Only Source Releases for Some Security Updates?

0 Upvotes

I have a question about installers. Once a release enters the security-fixes-only phase, what is the purpose of releasing only source files and not providing installers or other binary distributions?

Is it because they expect people to keep using that version without migrating for as long as possible?

For example, Python 3.13.17, released on October 21, still came with installers, but Python 3.13.18 was released with source files only.


r/learnpython • • 1d ago

Question about NumPy Array Slicing

1 Upvotes

I'm making a Discord Bot that runs Text Recognition on Images. The Hosting I use provides a hard 256 MB RAM limit. I need help understanding NumPy Array Slicing to optimise the code.

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ].copy()

image is a NumPy array (I'm cropping the image here)

Apparently NumPy keeps a reference to the original image array if I do just this:

image = image[round(0.075 * image_height) : round(0.4 * image_height), : ]

I'm slicing the image array, then reassigning it back to the image variable, but since NumPy keeps a reference to the original array, the original image isn't released from memory. Is this true? If so, is the first approach using .copy() better?

Right after this, I do this:

timeROI = cv.inRange(image, np.array([15, 145, 155]), np.array([95, 255, 215]))

# Filters Yellow-Green Pixels and creates a Binary Image (OpenCV uses BGR, not RGB)

Immediately after this, I do del image.


r/learnpython • • 1d ago

I can follow Python tutorials fine, but I freeze on a blank file — how did you actually break out of that?

0 Upvotes

I'm a second-year BCA (AI/ML) student in Jaipur, self-studying Python alongside college. Here's my embarrassing problem: I can follow a tutorial, understand every line while I'm watching it, and even tweak the example code — but the moment I open a blank file and try to build something of my own, my mind goes completely blank. I don't know where to start, what the first function should even be, or how to break the thing I want into pieces small enough to write.

I've built a couple of small things before (a little Telegram bot, some practice scripts), so it's not that I've never finished anything — it's that starting still feels like the hardest part every single time. Do you plan on paper first, or just start writing messy code and clean it up later? How do you decide what the first step is when the whole project feels too big to hold in your head at once?

And for people who got past this stage: was there one specific habit that broke it for you — building the same kind of project twice, copying a structure and filling it in, writing the steps out in plain words first, or something else? I don't want another tutorial recommendation, I want to know what actually changed the blank-file feeling for you.

No links or anything here — just a student trying to get from "I understand Python" to "I can actually start something in Python."


r/learnpython • • 2d ago

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

10 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 • • 1d ago

Confusing code min() max()

0 Upvotes

I'm debugging some code and I found this function ``` import math

   def Clamp(n, smallest, largest):
       return max(smallest, min(n, largest))

`` surely that code is just wrong? and needs to bemax([smallest, min([n, largest]))` by passing a list not unnamed args for default and key? I need a sanity check here.


r/learnpython • • 2d 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?


r/learnpython • • 1d ago

How to make this python script faster and able to run?

0 Upvotes

hey there, i m working on this python script: https://pastebin.com/kknURJij
and the main issue i m facing right now is its not running and i have been stuck in the terminal since so long...
i just want to ask how to make it faster so we can execute it.

Output when i run this script :

```DeprecationWarning: `langchain-community` is being sunset and is no longer actively maintained. See https://github.com/langchain-ai/langchain-community/issues/674 for details and migration guidance toward standalone integration packages.
from langchain_community.utilities import SQLDatabase.```

currently its stuck with this same terminal output.
My pc specs : Mac Air M1, Golden Gate 28

what i have tried :
Tried running on github codespaces but still not running but stuck with the same output.


r/learnpython • • 1d ago

Python CDP and MCP

0 Upvotes

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


r/learnpython • • 1d 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 • • 2d 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