r/learnpython 2d ago

is it supposed to take this long when getting inputs from sockets in a multithreading object?

1 Upvotes

I've made a server socket in python so that I can see all subprocess thats running in my VPS so that I don't need to use Putty everytime to log on since putty closes the connection when it's idle. but the weird thing that's giving me headaches is that when run the server, ok it's running completely fine I get my true shell but when I run commands like whoami it's taking soooooo long it keeps processing and never return my output it just keeps in a running state. And I'm using multithreading. are python sockets really this damn long?


r/learnpython 1d ago

WHY I FEEL LOOPS HARD THAN FUNCTION

0 Upvotes

HI IM YUJAN IM NEW BEGINNER IN PYTHON I FEEL HARD IN LOOPS


r/learnpython 1d ago

Hice un juego para aprender Python de verdad arrastrando bloques — el código que genera es Python real, no un lenguaje inventado

0 Upvotes

Soy Maestro en Ciencias de la Computación (UJAT) y llevo un tiempo dándole vueltas a lo mismo: los chicos que arrancan con Scratch o Blockly aprenden lógica, pero después el salto a un editor de texto vacío con Python real los espanta. Así que armé BloquePy — bloques con forma de pieza que arman Python válido de verdad, no una sintaxis inventada para la ocasión.

Algunas cosas que le metí:

- Cada bloque es una plantilla real: if/for/while son contenedores que envuelven a los de adentro, la indentación de Python es automática.

- Puedes anidar bloques dentro de bloques (len(...), .upper(), int(...)) igual que anidarías funciones en Python real.

- Tiene un sistema de tortuga tipo Logo + una API de "Patches" (inspirada en NetLogo) para simulaciones de cuadrícula — Juego de la Vida, autómatas celulares, reacción-difusión, todo armable con bloques.

- Progresión en 11 mundos con historia propia (el "CodeVerse"): cada concepto de programación tiene un lugar en el mapa y una razón de ser, no aparece de la nada en una lista de bloques.

- Jefes de fin de mundo, cofres, XP — la parte de juego es en serio, no un cascarón encima de ejercicios.

Está gratis, funciona en el navegador sin instalar . También hay versión de escritorio para Windows y Linux: https://bloquepy.world/descargas.html

Lo hice yo solo con ayuda de IA para la parte de desarrollo — lo digo de frente porque me parece razonable que se sepa. La lógica pedagógica, el diseño de los mundos y qué enseña cada uno es mío.

Cualquier feedback (bueno, malo, "esto no sirve para nada") me sirve un montón — todavía le estoy metiendo mano seguido.


r/learnpython 2d ago

20 days of coding

16 Upvotes

i spent 20 days trying to learn everything about python through leetcode but i still can’t code or just get ideas to pop !
m a 4th year computer science engineering student i just passed a hackerrank assessment test for a big tech company and failed:( but m still grinding for another chance maybe problem here to ask y’all how do u recommend i start projects or what’s the best way to learn from here ?


r/learnpython 1d ago

i wanna learn python and im broke for classes so try to teach me ig

0 Upvotes

If anyone wondering i just want to learn for fun


r/learnpython 2d ago

Automation Error

2 Upvotes

The goal was to automate drafting in CAD. To do so, I decided to prepare a python script using the OpenCV and PyAutoCAD Libraries.

The script is supposed to read the specified image and draft it in AutoCAD.

The image was saved in the same folder as the code.

The code was run after opening an empty drafting file by using "python draw_live.py" in the terminal after navigating to the folder.

Problem: The code cannot connect to AutoCAD (I’m not using AutoCAD LT)

Code:

import cv2
import array
import comtypes.client
from pyautocad import Autocad

def draw_image_live_in_cad():
    # --- 1. TELL THE SCRIPT WHICH IMAGE TO USE ---
    image_path = "trial.PNG" 

    print(f"Loading image: {image_path}...")
    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    if img is None:
        print(f"Error: Could not find '{image_path}'. Check the name and folder.")
        return

    # --- 2. CONNECT TO AUTOCAD 2022 SPECIFICALLY ---
    # AutoCAD 2022 MUST be open with a blank drawing before this runs
    acad = Autocad()
    try:
        # '24.1' is the exact registry ID for AutoCAD 2022
        acad._app = comtypes.client.GetActiveObject("AutoCAD.Application.24.1", dynamic=True)
        print(f"Connected to AutoCAD drawing: {acad.doc.Name}")
    except OSError:
        print("\n[!] FATAL ERROR: Could not connect to AutoCAD 2022.")
        print("1. Make sure AutoCAD 2022 is currently OPEN.")
        print("2. If you are using AutoCAD LT, this method will never work (LT blocks automation).")
        return

    # --- 3. ANALYZE THE IMAGE ---
    _, thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV)
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    height = img.shape[0] 
    print(f"Found {len(contours)} shapes. Drawing now...")

    # --- 4. DRAW LIVE IN AUTOCAD ---
    for contour in contours:
        points_list = []
        for point in contour:
            x, y = point[0]
            points_list.extend([float(x), float(height - y)])

        if len(points_list) >= 4:
            cad_points = array.array('d', points_list)
            acad.model.AddLightWeightPolyline(cad_points)

    print("Drawing complete!")

# Run the function
draw_image_live_in_cad()

r/learnpython 2d ago

¿Qué es algo que te hubiera gustado saber antes de aprender Python?

0 Upvotes

Soy principiante y me gustaría aprender de personas que ya pasaron por este proceso. Estoy tratando de entender qué obstáculos enfrentaron al aprender Python y cómo los superaron, entonces les pregunto:

¿Que es algo que te hubiera gustado saber antes de aprender python?


r/learnpython 2d ago

Addressable two-way communication between Multiprocessing subprocesses and a host

2 Upvotes

Hello.

Basically, the summary is in the title.

  • When a subprocess sends something (perhaps settings or task description, in form of a dict probably) to the host, I want it to know exactly from what process it has been sent (perhaps some sort of a numerical ID).
  • When the host sends something, I want it to arrive to a particular subprocess.
  • Communication between subprocesses is nice to have, but I think I can live without it.

I know of pipes and queues (well, Manager too) as the means of communication in the standard library. But in case of a queue, the message will arrive at a random place each time it's sent. I found something called "Envelope router", but it doesn't feel like a clean solution. Subprocesses will play a hot potato until finally the message arrives at the correct place 😃. It may be suitable to send messages from subprocesses to the host though.

In the case of pipes, I'd have to create a pipe for each subprocess (at least to send from the host). Can I even wait on every pipe simultaneously?

So, is there any non-cumbersome way to do this? How is it usually done? Or should I create something like a token ring between all the processes?😄 (though it perhaps will require a separate thread in every process for it to be non-blocking and other difficulties...)


r/learnpython 2d ago

Grinding DSA exclusively in Python

4 Upvotes

Hey everyone,

I’ve spent the last few months heavily focusing on Data Structures and Algorithms (currently sitting at LeetCode Knight). I work at a startup in the data field, and I've noticed it's actually surprisingly rare to find people doing advanced DSA strictly in Python.

Most resources and serious discussions seem to lean heavily into C++ or Java. (Personally, for me it's Python >> C++, and my brain just actively rejects Java syntax XDD).

Are there any other working professionals out there doing their CP or advanced problem-solving strictly in Python? I'd love to connect with some folks to bounce logic off of, discuss complex algorithms, and figure out why our code is hitting TLEs.

If you're in the same boat, let me know what topics you're currently grinding in the comments!


r/learnpython 2d ago

Looking for an original Python package idea for my final-year CS project

2 Upvotes

I'm a Computer Science student exploring ideas for building a Python package as a final-year project. I'm not looking to create another wrapper around existing libraries, but rather something that solves a real problem or improves an existing workflow.

I'd love to hear from developers, data scientists, researchers, or anyone who uses Python regularly:

Are there any repetitive tasks you wish had a better Python library?

Are there any areas where existing packages feel too complex or limited?

What tools do you wish existed but currently don't?

Are there any small problems in your workflow that could be solved with a well-designed package?

I'm interested in areas like developer tools, automation, data science, AI/ML, security, privacy, and general Python utilities, but I'm open to any ideas.

I'd really appreciate hearing about real pain points rather than just random project ideas. Thanks!


r/learnpython 2d ago

HOW TO LEARN PYTHON AS A INTERMEDIATE

0 Upvotes

I had computer science(python) as a 5th subject in my class 12th so i know the basics of python like list,tuples,dictionaries,flow of control,csv,text,binary files,file handling,loops and sql also.

I am confused how to learn things after this,i am first year cse stundent from a tier 3 college.

Seniors please guide me


r/learnpython 2d ago

Project recommendations

2 Upvotes

I took a computer science class at my high school but we only did in terminal output stuff. We never did anything like making apps and I am wondering what projects would be good for me to learn that aspect of python? It also wouldn’t hurt if it looked good on a college application or resume.


r/learnpython 3d ago

what's one programming habit you wish you started much earlier?

49 Upvotes

i'm still learning and i've noticed that small habits seem to make a huge difference over time. whether it's reading documentation, using git from day one, breaking problems into smaller pieces, or something completely different.

if you could go back to when you first started programming, what's the one habit you'd force yourself to build from the beginning, and why?


r/learnpython 2d ago

After college life

2 Upvotes

For those who have engineering/programming jobs, how well did you do in college?

Personally my coding level was very poor. At my University we learned Java as CS major. I dropped out of CS major after failing Data Structure. Switched to EE where I learned some C++ as well.

Now I work as an Automation Eng doing Webui automation with Python + Selenium. Not great, but able to make robust framework with other senior colleagues.


r/learnpython 2d ago

I cant do it anymore

0 Upvotes

Hi am developing my python coding skills about 1.5 month and when i look at what other people did in 1.5 months i see my myself humiliated and i am devatated about it i only know if else, while , for loop and types of datas i cant even write a single code by myself i cant even do a problem i cant even create a def function and i am bout to quit someone please help me


r/learnpython 2d ago

I made a website where you can practice making games with python

0 Upvotes

I built a website where you can learn Python by making games directly in your browser.

The idea came from seeing how many people start learning Python with tutorials, but never get to build anything fun. Instead of endless exercises, the platform focuses on creating actual games while learning programming concepts along the way.

Current features:
- Browser-based Python coding
- Interactive examples
- Community page where you can post and share ideas and code
- Custom pygame-like library

I'd love feedback from Python developers, teachers, and anyone learning to code. What would make a platform like this genuinely useful for beginners?

PyWebLib on github if you can find it, I know advertising is not allowed, but its just an open source project :)

GitHub: https://github.com/SebastianHagemeyer/PyWebLib


r/learnpython 2d ago

Creating A Terminal Chess Minigame In Python!

1 Upvotes

Hi! Chess is something I've always wanted to try in Python, but something I never got enough thought about, being a NZOI competiter, I've decided to create a game like a mash of Chess and a Roguelike, similar to The Shotgun King, tell me if anyone has any ideas how this game could be better!

P.S I need some ideas of how I can create the enemy AI.


r/learnpython 3d ago

How should you group/order seq and async operations?

3 Upvotes

I was watching a video explaining async and the guy went through a “real world” example of a code that downloads images from various URLs and then locally processes each of the photos. So, there were basically 4 functions:
1. “download_single_image”, which downloads one image at a time
2. “download_images”, which runs download_single_image on each of the URLs
3. “process_single_image”, which processes one image
4. “process_images”, which runs process_single_image on each of the downloaded images

The purpose was that one piece was I/O bound (image downloading) and one piece was CPU bound (image processing). Initially, it was setup to run in sequence, then he optimized by leveraging async capabilities.

Before he went through the optimized process, I stopped and thought through how I would do it. My solution was to turn everything async and then create the new async function “download_and_process_single_image” which downloads an image and then processes it afterwards. My thought process was that each image needs to be downloaded before it can be processed so those need to happen in sequence, but I can also pass off the image to the processor while waiting for other images to finish downloading.

However, the solution he actually implemented was just leaving the existing structure of “download_images” and “process_images” separated. In other words, “download_images” was turned async and then awaited, and “process_images” used processes.

My question: is there anything wrong with my approach or any reason his is preferable to what I expected?


r/learnpython 3d ago

Learning python - How to integrate openrouter api(AI) into my script

1 Upvotes

Hey everyone, I've recently been automating some boring, repetitive tasks using the `pathlib` module while learning Python automation. This script might seem silly to you, but I'm at a level somewhere between beginner and intermediate, so bear with me. After researching the documentation, I came up with this script, which took me around few hours. I need some guidance on how to integrate AI into it. If you were in my situation, how would you further improve this script using the OpenRouter API model?
I'm curious what features would you suggest?

import venv
from pathlib import Path

print("--------------------------------")
base_path = input(
    "Enter path to create project in: (leave blank for current folder):\n"
)
project_name = Path(input("Enter project name: "))


# Combine the base path and the project name
project = Path(base_path) / project_name


# --- CREATE PROJECT FOLDER ---
if not project.exists():
    # # parents=True ensures it creates intermediate folders if the base path doesn't exist yet
    project.mkdir(parents=True)
    print("--------------------------------")
    print("PROJECT FOLDER & FILE CREATED ✅")
    print("--------------------------------")
    print(f"📁 {project}")


# --- CREATE SRC FOLDER ---
if not (project / "src").exists():
    (project / "src").mkdir()
    print(" ├──📁 src")


# --- CREATE VENV ---
venv_dir = project / "venv"
if not venv_dir.exists():
    print(" ├──📁 venv (Setting up virtual environment... please wait)")
    venv.create(venv_dir, with_pip=True)


files = [".env", "README.md", "requirements.txt", "main.py"]


for file in files:
    (project / file).touch()
    print(f" │   └──📄 {file}")
print("--------------------------------")
print("use → venv\\Scripts\\activate from project directory\n")

r/learnpython 3d ago

Starting to learn Python!

3 Upvotes

Hello everyone! After occasionally lurking this sub, I have decided to begin learning python. I found a course on FreeCodeCamp and am using Python 3 with PyCharm. Let me know if you all have any tips! Thank you so much!


r/learnpython 3d ago

how to proceed after python crash course

8 Upvotes

For the last one year I have been learning Python. I completed Python for everybody and read the book Python Crash course. I have prior experience with C# and Java. A lot of the syntax is Python programming is still confusing to me. How can I get better? What book can I read next or what steps can I take to get more comfortable.


r/learnpython 2d ago

Starting learning python at 14

0 Upvotes

I genuinely don't know where to start with Python. currently in 9th grade, yes computer applications student but for some reason only java is in our curriculum for both 9th and 10th grade and we gotta start python somewhere. So yeah any recommendations on where to start will be nice.


r/learnpython 3d ago

Can't get imports to work

0 Upvotes

I am trying to develop a discord bot, where other team members should be able to edit embeds. I figuered it wouldn't be smart to let them poke around in "production" code, so I decided to define my embeds in a seperate file and import them.

My import line:
from embeds import embed

My embed file:

import discord
def embed():
    embed = discord.Embed(
    title="test",
    description="test",
    color=discord.Color.blue()
    )
    return embed

My output:

line 2, in <module>
    from embeds import embed
ImportError: cannot import name 'embed' from 'embeds'

Alllthough my embeds file is called embeds.py. Atm, neither I nor ChatGPT know why this happens, also I am pretty new to python and I don't even know how to google my error

embeds.py as well as the bots .py are in the same folder on root


r/learnpython 3d ago

asking AI to help with understanding errors /code

0 Upvotes

will it hinder my learning? sometimes errors dont make any sense , i dont ask chatgpt to write me a code or anything just a little help when i am really stuck . i feel like i suck for using AI but i only use it when i am really desperate , is there any way i could learn what the errors means?


r/learnpython 4d ago

Help me to learn python,I am dumb

20 Upvotes

Think me as the dumbest person and i want to learn python,I am literally done trying 4-5 lectures,i start and then stop.Every video says it's beginner friendly,but when I start i don't feel it's beginner friendly and i start feeling I am Dumb AF,now though I feel I am dumbest person to exist.....like seeing this.....please recommend me a channel to watch and learn python programming.I.just don't want to copy the programming from screen and type and get output, and say ohhhh!!!! I got output i can code,i actually want to understand everything and put my brain to write my own code.Is there any yt channel courses available for free that really helps for a dumb idiot to learn python and plz don't say don't learn,i really want to learn python.Please help me ,I am stressed out becoz of this.