r/pythonhelp • • 21h ago

Autopep8 issue upon launching VSCODE

1 Upvotes

Hello everyone, I am new to vscode and just started learning Python.

I have this issue where when I open vscode Autopep8 sends 3 error messages straight away.

https://imgur.com/a/ViLsoBs

I have tried things like: Selecting the correct interpreter( Not that it really matters I only use python global), uninstalling and reinstalling the extension, setting it as default formatter, changing user settings (JSON). I get error messages in the bottom right corner such as:

autopep8 client: couldn't create connection to server.

The autopep8 server crashed 5 times in the last 3 minutes. The server will not be restarted. See the output for more information.

Pending response rejected since connection got disposed.

Here are my settings.json:

{
    "workbench.colorTheme": "Dark Modern",
    "workbench.iconTheme": "vscode-icons",
    "editor.defaultFormatter": "ms-python.autopep8",
    "notebook.defaultFormatter": "ms-python.autopep8",
    "[python]": {
        "editor.defaultFormatter": "ms-python.autopep8"
    },
    "editor.formatOnSave": true,
    "autopep8.interpreter": [
        "C:\\Users\\Windows Desktop\\AppData\\Local\\Python\\pythoncore-3.15-64\\python.exe"
    ]
}

If anybody has a solution to this problem I would appreciate your help down in the comments.

Thanks in advance.


r/pythonhelp • • 1d ago

Import hook between AST and compile

0 Upvotes

I am trying to create an Import Hook inserted after the source code has been parsed into AST but before it is compiled. Looking for a way to keep using most of the existing Python import machinery but modify the source code before it is compiled.

So far I have the following code but how do I get access to the source code from the module in custom_import?

import builtins
from inspect import getmembers

base_imp = builtins.__import__

def custom_import(*args, **kwargs):
    module = base_imp(*args, **kwargs)
    for name, val in getmembers(module):
        print("in custom_import.", name, val)
    return module

builtins.__import__ = custom_import

print("in Main.py before import")
import Module1
print("in Main.py after import")import builtins

r/pythonhelp • • 3d ago

My UI/UX looks very smudged and jagged

2 Upvotes

So I am working on creating my own personal AI and my UI/UX looks very smudged, it is supposed to look like the UI/UX for an sci-fi generation ship. ASUS AI V1

import tkinter as tk
import math

# ==========================
# ASUS_v1
# ==========================

root = tk.Tk()

root.title("ASUS_v1")
root.geometry("1000x700")
root.configure(bg="black")

canvas = tk.Canvas(
    root,
    width=1000,
    height=700,
    bg="black",
    highlightthickness=0
)

canvas.pack(fill="both", expand=True)

angle = 0


def draw():
    global angle

    cyan = "#00FFFF"

    canvas.delete("all")

    # ==========================
    # TITLE
    # ==========================

    canvas.create_text(
        500,
        50,
        text="ASUS ONLINE",
        fill=cyan,
        font=("Consolas", 24, "bold")
    )

    cx = 500
    cy = 400

    # ==========================
    # OUTER RING
    # ==========================

    canvas.create_oval(
        250,
        150,
        750,
        650,
        outline=cyan,
        width=3
    )

    # Rotating markers

    for i in range(12):

        a = math.radians(
            angle + i * 30
        )

        x1 = cx + math.cos(a) * 220
        y1 = cy + math.sin(a) * 220

        x2 = cx + math.cos(a) * 250
        y2 = cy + math.sin(a) * 250

        canvas.create_line(
            x1,
            y1,
            x2,
            y2,
            fill=cyan,
            width=2
        )

    # ==========================
    # INNER RING
    # ==========================

    canvas.create_oval(
        325,
        225,
        675,
        575,
        outline=cyan,
        width=2
    )

    # ==========================
    # CENTER CORE
    # ==========================

    canvas.create_oval(
        450,
        350,
        550,
        450,
        fill=cyan,
        outline=cyan
    )

    canvas.create_text(
        500,
        400,
        text="ASUS",
        fill="black",
        font=("Consolas", 10, "bold")
    )

    # ==========================
    # SYSTEM PANEL
    # ==========================

    canvas.create_rectangle(
        20,
        120,
        180,
        360,
        outline=cyan,
        width=2
    )

    canvas.create_text(
        100,
        150,
        text="SYSTEM",
        fill=cyan,
        font=("Consolas", 12, "bold")
    )

    # ==========================
    # PROJECTS PANEL
    # ==========================

    canvas.create_rectangle(
        820,
        120,
        980,
        360,
        outline=cyan,
        width=2
    )

    canvas.create_text(
        900,
        150,
        text="PROJECTS",
        fill=cyan,
        font=("Consolas", 12, "bold")
    )

    # ==========================
    # ANIMATION SPEED
    # ==========================

    angle += 0.5

    root.after(25, draw)


draw()
root.mainloop()

ASUS_v1 memory.json:

{
    "user_title": "Sir",
    "voice_enabled": true,
    "hardware_thresholds": {
        "cpu_percent": 85.0,
        "ram_percent": 90.0
    },
    "protocols": {
        "house party": {
            "description": "Launch primary workstation suite",
            "paths": [
                "C:\\Windows\\System32\\calc.exe",
                "C:\\Windows\\notepad.exe"
            ]
        }
    },
    "dynamic_rules": {
        "run diagnostic": "audit_logs",
        "system status": "check_telemetry"
    }
}

r/pythonhelp • • 4d ago

Question in coding Text RPG

3 Upvotes

I am a hs student in a Computer Science course and I’m working on a personal project where I’m creating a Text RPG similar to those AI generated & run apps but without any AI and I’m currently stuck. I’ve worked out the randomised character creation (Name, Class, Strength, Dexterity, Wisdom, Intelligence, Charisma, Constitution, HP, AC, Initiative, Special Attribute/Spell, Power Level, & Catchphrase).
Now I’m working out how to code the actual Game part. I’m making a sort of encounter table (1-100) that randomises the number of encounters (10-50) and all encounters (Monster/Creature, Loot, Town, NPC/Quest, Environmental Events, & Rare Encounters) in addition to a randomized boss at the end of the game (1-20), but I don’t know how to code that many randomized inputs without mixing up my variables.


r/pythonhelp • • 4d ago

Python beginner!!

2 Upvotes

Beginner here: how would you structure my nested if statements in a two-step login program?

Hi all, I'm about 3 weeks into learning Python (Python for Everybody on Coursera) and just finished my first small project: a login program that asks for a passcode, then a second passcode, then lets the user pick a report.

My main question is about structure. I have nested if statements, and the second user repeats the same checks in a separate elif branch. Here's a trimmed version of the layout:

admin_login = input("Enter Passcode")

if admin_login == boss_code:
second_pass = input("enter second passcode")
if second_pass == boss_secondcode:
report = input("enter report number")
if report == "1":
print("report 1")
elif report == "2":
print("report 2")
elif admin_login == ass_code:
# same second-passcode and report checks repeated here

I'd love feedback on:

  1. Is the code organized in a clear, readable way?
  2. Is there a cleaner way to stack or avoid repeating these nested ifs, using only what a beginner would know (no classes yet)?

Full code and README are here: https://github.com/tylerkilgore148-can/python_learning_projects

I know the passcodes are stored in plain text, which is just for practice. I plan to look at getpass and hashing next. Beginner-friendly tips are very welcome, and thanks for reading!


r/pythonhelp • • 5d ago

why does python make sense in tutorials but not in actual coding

5 Upvotes

I'm a first year student learning Python rn and I swear everything makes sense when someone explains it but the moment I try to solve a question on my own, my brain just stops working is this normal in the beginning or am I missing something? how did you guys get better at solving problems without looking at the solution??


r/pythonhelp • • 5d ago

When should I avoid using list comprehensions in Python?

2 Upvotes

Hi all! I'm new to Python and recently learned about list comprehensions. They seem cool, but I keep hearing that there are times when I shouldn’t use them. For example, if I have a more complex operation that involves several conditions, would a traditional loop be clearer? Here’s a simple example: trying to filter out even numbers from a list of numbers but using nested conditions. Can someone explain when it's better to stick with a loop for readability? Thanks!


r/pythonhelp • • 7d ago

Title / Subject: Recovering original Python source from Cython-compiled Windows installer after total HDD failure

1 Upvotes

​

Hi everyone,

I’m looking for advice on whether it’s possible (and realistic) to recover the original Python source files from a Windows software installer I still have.

**Situation**

My primary HDD suffered a complete, unrecoverable failure. All of my raw project files (source code, assets, intermediate files, etc.) are gone. The only remaining artifact of the project is the Windows installer / executable that I used to distribute the software.

**Technical details**

- The application was written in Python.

- I used **Cython** to compile / protect the code (the .py files were turned into compiled extensions / encrypted / obfuscated form as part of the build).

- The final deliverable is a Windows installer (or standalone executable package).

- This represents over 15 years of work. While modern AI tools could speed up a rewrite, I would strongly prefer to recover the original source if there is any viable path.

**What I still have**

- The complete Windows installer / executable package.

- No original .py files, no intermediate Cython outputs, no project folder, and no backups of the source.

**What I’m hoping for**

Any realistic options, tools, or techniques that might allow me to:

- Extract or reconstruct the original (or close-to-original) Python source from the Cython-compiled binaries / installer, or

- At least recover meaningful portions of the logic, structure, or key modules so a full rewrite is not required from scratch.

I’m aware that Cython compilation (and any additional packing/encryption I applied) makes this non-trivial, and that perfect recovery is often impossible. I’m mainly looking for an honest assessment of what’s feasible and any recommended tools, approaches, or communities that specialize in this kind of recovery / reverse-engineering of Cythonized Python applications.

If anyone has experience recovering source from Cython extensions, PyInstaller + Cython packages, or similar compiled Python Windows builds, I’d be very grateful for any pointers, tool recommendations, or realistic expectations.

Thank you in advance for any help or direction you can offer.


r/pythonhelp • • 9d ago

Recreating image look with Pillow

Thumbnail drive.google.com
0 Upvotes

There's an image effect in powerpoint I would love to use in my python projects. The effect is called "Texturizer", and it gives the picture a grainy, paper-y look. There's an example in the link provided. Feel free to try it yourself too if you've got powerpoint: select a picture, go to "picture format", then click on "Artistic Effects" and select "Texturizer"

I want to recreate that effect in pillow. It has to be deterministic (can't be 100% random cause I'm applying it to video frames). I don't know if making an image texture, then applying it, is the best option, for it can cause tiling (as in the examples from powerpoint's filter). I'm open to any kind of ideas.

I'm all ears!


r/pythonhelp • • 9d ago

Code but wht is it and how do we really know it works

0 Upvotes

from io import BytesIO wht does this do is it even right should it be better and wht functions does it do like...


r/pythonhelp • • 13d ago

When should I avoid using list comprehensions?

9 Upvotes

I started using list comprehensions in my project, but I feel confused about when they are actually a good fit. I tried to use one for a task that involves checking conditions on nested lists, and now my code is harder to follow. Is there a guideline for when it's better to stick with regular loops instead? I want my code to be readable, but I'm not sure I've got the balance right.


r/pythonhelp • • 19d ago

Performance issue when running python file

7 Upvotes

Hey everyone,

I'm experiencing a performance drop when running a Python file. I'm using VS Code on Windows 10 while learning to program.

When I hit the run button, the runtime of the program is 5.0 seconds, even though it should execute in roughly about 0.003 milliseconds.

I have tried switching to older versions like 2025.6.1, but that didn't work.

Any solutions to that problem?


r/pythonhelp • • 19d ago

How to pass a string of keyword arguments into a function

3 Upvotes

Having encountered, the seemingly impossible in Python, difficulty of passing a string of keyword arguments into a function like this:

args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='var4'"

def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
    print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")

myFunc(args_in)

One solutions I found was to use eval():

eval("myFunc(" + args_in ")") 

although I am informed that this is the work of the devil and should be avoided at all costs.

Next attempts were to convert the "string" into a dict{} and pass **dict, however all methods for doing this failed when any of the arguments contained a comma ','.

However a fully working solution to this was finally provided to me on the discuss.python.org forum:

args_in = "arg1 = 'var1', arg2 = 2, arg3 = True, arg4='va,r4'"

def myFunc(arg1=None, arg2=None, arg3=None, arg4=None):
    print(f"{arg1=}, {arg2=}, {arg3=}, {arg4=}")

def str2dict(str_in: str) -> dict[str, str]:
    import ast
    return {pair.arg: ast.literal_eval(pair.value)
        for pair in ast.parse(f"f({str_in})").body[0].value.keywords}

myFunc(**str2dict(args_in))

Unfortunately due to rather rude and overly zealous moderation on there that solution was deleted. Hence the reason for publishing it here for the archive and in case it helps someone else in the future.


r/pythonhelp • • 20d ago

What's everyone using for Python coding these days?

3 Upvotes

I mostly code with python and i've been thinking about changing my setup.

I'm not looking for anything too complicated. Mainly something that can understand the project, help debugging and make changes across multiple files without me having to explain the whole thing every time.

If you mostly work with Python what does your setup look like these days and how it been working for you?


r/pythonhelp • • 20d ago

Advise needed on python

1 Upvotes

Is it good idea to learn python on YouTube if not what's the best way to learn python


r/pythonhelp • • 22d ago

is SikuliX still maintained enough to build on or has everyone moved to something else?

2 Upvotes

I inherited a SikuliX suite that's been running since 2021 against a windows desktop app, and i have to decide whether to invest in it or replace it. It’s 180 scripts, about 120 still pass reliably, the rest fail on screenshot matches that no longer match. when i dug into the causes it was a windows 11 theme change, a DPI difference between our CI box and the dev machines, and a font rendering change that shifted text by 2 pixels. not one of those is a defect in our product, and all of them cost me a week.

The project isn't dead exactly, there are commits but the documentation is old, most of what you find searching is from 5 or 6 years back, and i can't tell whether the people maintaining it are building or keeping the lights on. We’re wighting it against going back to the accessibility tree with FlaUI. It works properly on maybe 60 percent of our screens and fails completely on the custom drawn ones, which is exactly where SikuliX earns its keep.

Ther are the newer vision based ones like Askui and a few others, which do roughly the job SikuliX does but with a model doing the matching instead of pixel comparison. In principle that's immune to the DPI and font problems that broke us. In practice i would want to know whether it's a different mechanism or the same idea with wider tolerance. Or just keep SikuliX and pin everything.

Has anyone here migrated off SikuliX recently? did what you moved to held up against theme and DPI changes? Thanks for sharing!


r/pythonhelp • • 22d ago

Run button taking a lot of time to run the file

2 Upvotes

Whenever I am trying to click the run button for a python code, it takes around 10-12 seconds to run and if I trigger the file directly from termina, it gets done in an instant. Is there any fix for this? I removed most of the extensions and still the same issue


r/pythonhelp • • 26d ago

What's going on?

3 Upvotes

I have some code I need to do a lot of calculations and I tried speeding it up by parralelizing with multiprocessing, but I'm running into a few issues. Using 5 processes (my computer has 6 cores) is giving me a speed boost of 50-100x, but for some reason the results are slightly wrong. I'm trying to fix that problem, but I'm also wondering where the massive speed boost came from, because that implies there's something else making it go faster besides parralelizing. If I could go back to a single thread but keep most of that speed, that would be great. For context, I'm doing some high-precision calculations with the decimal libraray but mostly just a lot of math in a cythonized function. The time it takes went from ~10 hours to 10 minutes.


r/pythonhelp • • 28d ago

How to make a working exe file using pyinstaller

3 Upvotes

Here is my file set up, I can't seem to get it to work no matter what.

StarDanceProject_FLStudioGrind/
├── .ruff_cache/
├── .vscode/
├── Game/
│   ├── __pycache__/
│   ├── Images/
│   ├── Maps/
│   ├── Sounds/
│   ├── BetaStats.py
│   ├── Dialogue.py
│   ├── Main.py
│   ├── Settings.py
│   ├── SOUNDS.py
│   ├── Tiles.py
│   ├── Timer.py
│   ├── UI.py
│   └── Waiver.py
├── .gitattributes
├── desktop.ini
└── README.md

r/pythonhelp • • 29d ago

Subclass mysql.connector

4 Upvotes

Any idea what I am doing wrong when trying to subclass mysql.connector like this:

import mysql.connector

class Database(mysql.connector.MySQLConnection):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

db = Database()
db_conn = db.connect(host = '...', database = '...', user = '...', passwd = '...')
print(f"{db_conn=}")

db_conn always returns None.

Edit: code above corrected to include connect() method

Edit2: Further to comment by brasticstack connect() method removed again.


r/pythonhelp • • Sep 19 '26

Using AI (ChatGPT/Claude) to learn Python — is this fine or am I sabotaging myself?

0 Upvotes

Been learning Python for a bit now (working through CS50P) and I've started leaning on AI tools a lot when I get stuck — debugging, explaining errors, even generating chunks of code when I'm short on time.

It's helping me move faster for sure, but I've got this nagging feeling I might be skipping the "struggle" part that actually makes concepts stick. So a few questions for people who've been through this:

  1. Is using AI while learning actually fine, or does it hurt long-term retention/problem-solving skills?
  2. If I should cut back, how much? Like — full cold turkey, or just use it for specific things (explaining errors vs. writing code for me)?
  3. If I do cut down, how do I actually get better at writing code on my own? Any habits, resources, or exercises that helped you build real problem-solving muscle instead of just pattern-matching to AI suggestions?

Would really appreciate advice from people who've either made this mistake or found a good balance. Trying to actually become a solid programmer, not just someone who can prompt their way to working code.


r/pythonhelp • • Sep 16 '26

QStateMachine with Conditional Transitions - How To Do Properly?

Thumbnail
1 Upvotes

r/pythonhelp • • Sep 14 '26

Library function which is the inverse of 'os.path.expanduser' ?

0 Upvotes

I'm running python 3.13.5.

Is there some sort of standard python library function which behaves as the inverse of 'os.path.expanduser'?

For example, if the current user's HOME directory is "/home/theuser", then we have this:

os.path.expanduser('~/a/b/c')
=> returns "/home/theuser/a/b/c"

I'm wondering whether there also might be any existing python library function which is the inverse of this and that works as follows:

some_sort_of_function("/home/theuser/a/b/c")
=> returns "~/a/b/c"

AND PLEASE NOTE: There often are people who lazily and disrespectfully refuse to read entire reddit posts before writing their reponses, and therefore, I'm making a point now to ask that before you start to write any reply here, please carefully and non-lazily read this *entire* post -- including the following, which is something that I want all potential responders to understand:

I know how to easily write my own function that works in this manner. However, I am clearly and SPECIFICALLY (!!!) asking whether or not there already is an existing python function which works this way, and if so, I'd like to know what this function might be ... and I am NOT (!!!) asking how to write my own function which does this.

Thank you very much in advance.


r/pythonhelp • • Sep 12 '26

Built a Python scraper that handles pagination automatically — here's what I learned

5 Upvotes

I've been learning Python through CS50P and wanted a real project, so I built two scrapers: one for job listings and one for product prices off an e-commerce site.

The job scraper was pretty straightforward — grabbed title, company, and location, dumped it to CSV, worked first try on about 100 listings.

The product scraper was the harder one. The site spreads results across pages (6 products per page, ~20 pages), so my first version only ever grabbed page 1. Took a bit of digging to figure out the pagination pattern and loop through all the pages properly. Once I fixed that it pulled all 117 products cleanly into a CSV.

Biggest thing I learned: it's easy to write a scraper that works on the first page and assume it's done — always check if the site paginates before you call it finished.

Code's on GitHub if anyone wants to see it: github.com/sarimkhan08

Curious if anyone here has tips for handling scrapers on sites that use infinite scroll instead of numbered pages — that's the next thing I want to tackle.


r/pythonhelp • • Sep 12 '26

Python Program that Green Screens a Video over the Desktop

2 Upvotes

Hello, I've been trying to figure out a way to make a python program that can play a green screen video that plays over the desktop/screen, with the green chromad out to show the screen. I attempted it with tkinter, but wasn't able to get anywhere with the chroma keying. Would anyone know if/how this would be possible? Thank you!