r/pythonhelp • • 2d ago

Threadline: a step-through visualizer for the GIL, threading, and asyncio

0 Upvotes

Threadline shows Python concurrency as a timeline where each OS thread is its own lane, and you step through it one event at a time. You can see which thread holds the GIL, when it's released, and why CPU-bound threads take turns instead of running in parallel.

Current Python scenarios:

CPU-bound work on threads vs multiprocessing

I/O-bound threads releasing the GIL while they wait

An asyncio event loop stalled by a blocking time.sleep(), and the fix with asyncio.to_thread

The same CPU-bound workload on a free-threaded (no-GIL) build

Each scenario is checked against a runnable Python program, so the timeline matches real behavior.

Target Audience

Developers who use threading or asyncio but have never had a clear mental model of what the interpreter is doing. It's a learning tool, not a profiler or production debugger.

Comparison

Profilers like py-spy and viztracer show what your program did after the fact. Threadline shows small, curated scenarios step by step, focused on explaining why the runtime behaves that way. Most existing explanations of the GIL are static diagrams or blog posts. This one is interactive.

Free,no signup. Feedback on accuracy is very welcome, especially on the free-threaded scenarios.

Link: threadline-be-fast.vercel.app


r/pythonhelp • • 3d ago

python breaks for some reason when I rename a project

3 Upvotes

Hi, python newbie here, and I have a very weird problem which is that whenever I rename a project, python refuses to run it because of "cannot run program "/Users//PycharmProjects/WelcomeScreen/.venv/bin/python" (in directory "/Users//PycharmProjects/Blackjack_but_working"): Exec failed, error: 2 (No such file or directory)"

(i censored my name for privacy reasons but otherwise that is the error)

plz help


r/pythonhelp • • 4d ago

python socks5 proxy server lib

2 Upvotes

is there library wich handless socks5 protocol for me and allows me to decide tru wich socks5 proxy to route each connection and to wich ip wich domain to resolve by giving it functions wich it calls when need to connect/resolve domain tru my proxy

example function that it gives(its not fully python syntax since python typing system is hard to read):

    run(
      ip,port,user,pass,
      resolve(domain)->ip, #called when client tryes to resolve domain and return ip it will get 
      connect(ip)->(ip,port,user,pass) #called when client wants to connect to specific ip and returns ip,port,user,pass of socks5 proxy tru wich it will connect,if user and pass is None connects without them
    )

r/pythonhelp • • 11d ago

Narrowing down this `ast` selection

Thumbnail reddit.com
1 Upvotes

r/pythonhelp • • 11d ago

Mr.Veeraragavan

0 Upvotes

I am loading few large size binary files (70 MB19 nos. look_up tables) in Main using more than 2/3 python files. On completion of the loading, I have to take up a series of search (in 3 or more threads) and arrive at the solution. I am using array.fromfile for loading which does not wait for loading completion. Hence, it fails saying array out of bounds. How do I delay the start of search, just till the loading is completed.


r/pythonhelp • • 12d ago

Need advice to implement the winning logic for my Tic-Tac-Toe game

1 Upvotes

Hey everyone, I'm new to Python and working on my Tic-Tac-Toe project, which is almost finished. I just need to set up the winning logic. But I don't know whether to use a dictionary to store winning positions or an if-elif-else chain. What programming concept would you recommend? Feel free to draw attention to anything I've forgotten to implement in the playing logic of the code:

import random

playing_field = [1, 2, 3,
                 4, 5, 6,
                 7, 8, 9]

def display_field():
    print("")
    print(f" {playing_field[0]} | {playing_field[1]} | {playing_field[2]}")
    print("---+---+---")
    print(f" {playing_field[3]} | {playing_field[4]} | {playing_field[5]}")
    print("---+---+---")
    print(f" {playing_field[6]} | {playing_field[7]} | {playing_field[8]}")
display_field()

print("********************Welcome to my Tic-Tac-Toe game********************")

game_running = False
markings = ["X", "O"]
player_past_movements : list[int] = []
ai_past_movements : list[int] = []
ai_mark = ""
player_mark = ""
player_move = 0
ai_move = 0




while True:
    menu_input = int(input("0 - Quitting\n1 - Continue\n"))

    if menu_input == 0:
        game_running = False
        print("See you next time. ")
        break
    elif menu_input == 1:
        game_running = True
    else:
        print("Invalid input") 

    player_mark = input("Select a mark: ")  
    
    while game_running == True:    
        if player_mark == "O":
            player_mark = markings[1]
            ai_mark = markings[0]
        elif player_mark == "X":
            player_mark = markings[0]
            ai_mark = markings[1]
        else:
            print("Invalid input")
            break

        ai_move = random.randint(1, len(playing_field) - 1)
        if ai_move in ai_past_movements:
            continue
        elif ai_move in player_past_movements:
            continue
        else:
            ai_past_movements.append(ai_move)
            
        print(f"Move chosen by AI: {ai_move}")
        player_move = int(input("Make your move: "))

        if player_move == ai_move:
            print("Cannot insert your mark on the same field, marked by the AI. ")
            continue
        elif player_move in ai_past_movements: 
            print("AI has already done that move. ")
            continue
        elif player_move in player_past_movements:
            print("You have already done that move. ")
            continue
        else:
            player_past_movements.append(player_move)
        
        match player_move:
            case 1:
                del(playing_field[0])
                playing_field.insert(0, player_mark)         
            case 2:
                del(playing_field[1])
                playing_field.insert(1, player_mark)
            case 3:
                del(playing_field[2])
                playing_field.insert(2, player_mark)
            case 4:
                del(playing_field[3])
                playing_field.insert(3, player_mark)
            case 5:
                del(playing_field[4])
                playing_field.insert(4, player_mark)
            case 6:
                del(playing_field[5])
                playing_field.insert(5, player_mark)
            case 7:
                del(playing_field[6])
                playing_field.insert(6, player_mark)
            case 8:
                del(playing_field[7])
                playing_field.insert(7, player_mark)
            case 9:
                del(playing_field[8])
                playing_field.insert(8, player_mark)

        match ai_move:
            case 1:
                del(playing_field[0])
                playing_field.insert(0, ai_mark)
            case 2:
                del(playing_field[1])
                playing_field.insert(1, ai_mark)
            case 3:
                del(playing_field[2])
                playing_field.insert(2, ai_mark)
            case 4:
                del(playing_field[3])
                playing_field.insert(3, ai_mark)
            case 5:
                del(playing_field[4])
                playing_field.insert(4, ai_mark)
            case 6:
                del(playing_field[5])
                playing_field.insert(5, ai_mark)
            case 7:
                del(playing_field[6])
                playing_field.insert(6, ai_mark)
            case 8:
                del(playing_field[7])
                playing_field.insert(7, ai_mark)
            case 9:
                del(playing_field[8])
                playing_field.insert(8, ai_mark)
            
     
        
        display_field()    

r/pythonhelp • • 26d ago

Autopep8 issue upon launching VSCODE

1 Upvotes

EDIT: The issue was Autopep8's Python interpreter version, I was using 3,15 before and after trying 3.14 issue was resolved.

  1. The autopep8 extension runs a small background server written in Python, using the interpreter set in autopep8.interpreter.

  2. That interpreter was Python 3.15, which removed typing.no_type_check_decorator

  3. A library bundled inside the extension (typing_extensions) still tried to use it, so the server crashed on startup.

  4. VS Code retried 5 times, gave up, and showed the error popups.

  5. Installed an older Python (3.14) that still has the removed function, which meant getting around the blocked installer (the PythonBA.dll error) by using py install 3.14 or winget.

  6. Pointed autopep8.interpreter in settings.json at that 3.14 python.exe, so only autopep8 uses the older version while the code can still run on 3.15.

  7. Ran Developer: Reload Window so VS Code restarted the extension with the new setting.

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 • • 27d ago

Import hook between AST and compile

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

My UI/UX looks very smudged and jagged

3 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 • • 29d 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 • • 29d 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 • • Oct 16 '26

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

6 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 • • Oct 15 '26

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 • • Oct 14 '26

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 • • Oct 12 '26

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 • • Oct 11 '26

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 • • Oct 08 '26

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 • • Oct 01 '26

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 • • Oct 01 '26

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 • • Oct 01 '26

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 • • Oct 01 '26

Advise needed on python

0 Upvotes

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


r/pythonhelp • • Sep 29 '26

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

5 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 • • Sep 29 '26

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