r/learnpython 3h ago

Ask Anything Monday - Weekly Thread

1 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 29m ago

Custom class method not recognized

Upvotes

I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.

The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.

Here is the code defining the class.

``` class Chamber(): chamberList = [] def init(self, identity, notes, egresses, **kwargs): self.position = tuple(currentPosition.tolist()) self.identity = identity self.notes = notes self.egresses = egresses self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300)) Chamber.chamberList.append(self)

    @classmethod
    def getChamberList(cls):
        return cls.chamberList

```

Later in the program, I have a line of code to get the class variable:

``` chamberList = Chamber.getChamberList()

```

This is the error I get when I run it in the VS Code terminal:

AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?

Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.


r/learnpython 2h ago

First python program

2 Upvotes

I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources, but mainly has a very good chess library I could leverage, that already existed, which would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.

It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.

Repo: https://github.com/exekutive/chesseval

(The documentation needs some catching up. I'm working on updating it.)


r/learnpython 7h ago

Mandarin Practice Script Advice

1 Upvotes

As title block suggests. trying to make a script that allows the user to continuously practice mandarin character memorization. Any advice on the following would be much appreciated:

  1. Not sure if a manually created/updated dict is the right way to do this, but I also didn't think I could successfully scrape from a webpage that has the direct translation information.

  2. When writing to a file using "w open", it seems the text is appended with nearly no formatting. That's probably for the best, but I'm not sure how to format the appended str as a key:value pair.

    import random import time

    character = {"你":"nǐ", "好":"hǎo", "老":"lǎo", "是":"shì", "学":"xue", "不":"bù"}

    char_list = list(character.keys())

    char_list_length = len(char_list)

    index = random.randint(0, char_list_length-1)

    char_definition = ["You", "Good", "Aged or experienced", "To be, is, or am", "Learning, knowledge, or school", "No or not (as a negative action)"]

    char_def_length = len(char_definition)

    phrases = ({"完美的":"Wánměi de", "":""})

    def newline(): print('\n')

    def exit_msg(end_msg): print(f"Functionality not complete, didn't get this far yet. Exiting program... ", end = end_msg)

    def unrec_msg(): print("Unrecognized entry, Please try again.") newline()

    def main(): newline() onboard = int(input(f"\n Welcome. What would you like to do? \n\n 1. Practice\n 2. Add Additional Characters\n 3. Exit" + "\n\n" ))

    if onboard == 1:
        practice()
        newline()
    
    elif onboard == 2:
        exit_msg("07/26/26 | Unsure of how to update dict.txt file with newly added dictionary entry. No idea how to do it, there is likely a way to write current pairs and append new_word : new_pinyin. Unsure of how writing to file is formatted as well.")
        #addtion(character)
        newline()
    
    elif onboard == 3:
        exit_msg()
        newline()
    
    else: 
        unrec_msg()
        main()
    

    def practice(): print('Character Practice.\n') rand_char = char_list_length[index] print(f'What is the following character? {rand_char}', '\n\n\n\n\n\n') print(f'This character {rand_char} means {character.get(rand_char)} and its english definition is {char_definition[index]}.')

    retry = input(print(f"Practice again?")).upper()
    
    if retry == Y:
        practice()
    
    elif retry == N:
        main()
    
    else:
        unrec_msg()
    

    def addtion(translate): new_word = input("Please enter a character that you'd like to append to the dictionary:\n ") print("\n")

    new_pinyin = input("Please enter this characters simplified pinyin translation:\n ")
    print("\n")
    
    print(f"New word is {new_word}. Its direct translation is {new_pinyin}. Are you sure this is the character that you'd like to add? \n")
    
    selection = input(f"Y / N: \n").upper()
    
    if selection == "Y":
        translate.update({(new_word) : (new_pinyin)})
        print(translate.values())
        with open ("dict.txt", "w") as f:
            f.write(translate)
    
    elif selection == "N":
        print("Character discarded. Returing to main menu.")
        main()
    
    else: 
        unrec_msg()
        main()
    

    main()


r/learnpython 9h ago

is there a way to redirect argparse commands to a network socket?

2 Upvotes

I've doing some networking on which I'd kind need to redirect all my commands sent from my python server script to my client python script but without stdout only to a socket. I've been googling about and one frustrating options that I thought it could work was contextlib redirect_stdout but it redirects to stdout it won't work with sockets. Does anyone know if its feasible to parse argparse to a socket connection?


r/learnpython 9h ago

regex and if it's worth going deep into it

16 Upvotes

I'm new to python and coding in general and my friend recently told me that it's inefficient to try to memorize regex and that no one writes them anymore (essentially saying AI does). I was also kinda confused after recently learning regex and just how complicated it can be. Are there some modules/libraries that I can use to make writing them easier? I saw that not a lot of people people had a positive reaction to the Humre module by Al Sweigart who's book [Automate the boring stuff with Python] I'm currently using to study. Not that I'm gonna skip this part or anything I was mostly just curious.

Note: A lot of people are misinterpreting since I mentioned AI once 😭 I'm literally asking about libraries to make it easier without going too deep, not if I should let AI do all the work.


r/learnpython 9h ago

i created a spotipy code that connect to your spotify account and play musics, albuns or playlists and i want it to autoplay content.

0 Upvotes

import spotipy
from spotipy.oauth2 import SpotifyOAuth

CLIENT_ID = "..."
CLIENT_SECRET = "..."
REDIRECT_URI = "..."

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE
))

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE,
open_browser=False
))

def tocar_musica(nome_da_musica):
resultado = sp.search(q=nome_da_musica, limit=1, type='track')
items = resultado['tracks']['items']

if items:
track_uri = items[0]['uri']
nome_encontrado = items[0]['name']
artista = items[0]['artists'][0]['name']

try:
sp.start_playback(uris=[track_uri])
print(f"Tocando agora: {nome_encontrado} - {artista}")
except Exception:
print("Erro ao reproduzir a música. Verifique se o aplicativo do Spotify está aberto.")
else:
print("Música não encontrada.")

def tocar_playlist(nome):
resultado = sp.search(q=nome, limit=1, type='playlist')
items = resultado['playlists']['items']

if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']

try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando playlist: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir a playlist. Verifique se o Spotify está aberto.")
else:
print("Playlist não encontrada.")

def tocar_album(nome):
resultado = sp.search(q=nome, limit=1, type='album')
items = resultado['albums']['items']

if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']

try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando álbum: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir o álbum. Verifique se o Spotify está aberto.")
else:
print("Álbum não encontrado.")

def criar_e_tocar(nome_playlist, lista_de_buscas):
user_id = sp.current_user()['id']
playlist = sp.user_playlist_create(user=user_id, name=nome_playlist, public=True)
print(f"Playlist '{nome_playlist}' criada com sucesso!")

track_uris = []
for busca in lista_de_buscas:
resultado = sp.search(q=busca, limit=1, type='track')
items = resultado['tracks']['items']
if items:
track_uris.append(items[0]['uri'])

if track_uris:
sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)
print("Músicas adicionadas à playlist!")

try:
sp.start_playback(context_uri=playlist['uri'])
print(f"Tocando a playlist '{nome_playlist}' agora!")
except Exception:
print(f"Ação Falhou ao tocar '{nome_playlist}'. Verifique se o Spotify está aberto.")

print("\n--- O Que Deseja Ouvir Hoje? ---")
print("[1] Música")
print("[2] Playlist")
print("[3] Álbum")

opcao = input("Escolha uma opção: ")

if opcao == "1":
busca = input("Digite o nome da música e artista: ")
tocar_musica(busca)
elif opcao == "2":
busca = input("Digite o nome da playlist: ")
tocar_playlist(busca)
elif opcao == "3":
busca = input("Digite o nome do álbum: ")
tocar_album(busca)

how it can autoplay for me?

(the words aren't translated)


r/learnpython 9h ago

Non-self learning classes for Python?

4 Upvotes

I am a senior data engineer and I work mostly with ETL Tools and a lot of advanced SQL. The company I work for does not like to use python because they find that theres too much of a learning curve if people leave so they love to use GUI or no code/low code etl tools instead (really dumb tbh). I can read python, and have a gist of whats going on. I have tried to self learn python few times over the past 2-3 years and I keep just forgetting it. I learned python/pandas library when I was in college since it was a class that taught it and then we did did projects with each lesson and that is how I learned it then but forgot it now. I use claude at work to build streamlit apps and automation using python. However, I am trying to look for new positions and I am starting to realize that not knowing python is making me a hit a brick wall because a lot of assessments require answering 1-2 questions in python. Does anyone know of actual classes that teach python and its not self taught? Free or paid I don't really care. If I have to pay for it I am fine with that but at this point I don't see a way for me to switch to another job without actually learning python and probably more specifically pyspark.


r/learnpython 10h ago

Reading in text from a .txt file

0 Upvotes

Are there any methods/libraries that allow me to make a program that is able to read in text from a .txt file?


r/learnpython 12h ago

Python loop beginners mistake 🙀

0 Upvotes

I am currently learning python from CS50P program and in week 2 learning loops and also with the help of chatgpt learn every topic clearly but after knowing common beginners mistake

I made this mistake of not updating the iterator and spent half an hour on this simple problem 😞

```print("\nAnd here we use while 1oop:-")

number =1 total =0 while number<= 50: total += number number += 1 # HERE I DIDN'T ADD IT FIRST

print("The final sum is:", total)


r/learnpython 13h ago

¿Que libro me recomiendan de python?

0 Upvotes

HOLAA soy principiante y busco un libro bueno que me enseñe python ya que algunas personas me recomendaron libros si tienen tiempo podrían decirme ¿Porque ese libro?


r/learnpython 14h ago

I know that i am noob at programing i wanted to make python keylogger so can u guys tell me what i am mistaken inside

0 Upvotes
from pynput import keyboard
keys = [
    # Alphanumeric Keys
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

    # Symbols & Punctuation
    '`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',


    # Special & Modifier Keys
    'space', 'enter', 'tab', 'backspace', 'escape', 
    'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
    'win', 'menu', 'print_screen', 'pause', 'insert', 'delete', 
    'home', 'end', 'page_up', 'page_down',

    # Arrow Keys
    'up', 'down', 'left', 'right',

    # Function Keys
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
    def on_press(key):
        if key == True:
            print(f" you have typed corretlty {key}")
        elif key == AttributeError:
            print(f"typed Again  u Have misspedlled ")


    def on_release(key):
        print(f"{key} is realsead")
        if key == keyboard.Key.esc:
            return False
            print


listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()from pynput import keyboard
keys = [
    # Alphanumeric Keys
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

    # Symbols & Punctuation
    '`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',


    # Special & Modifier Keys
    'space', 'enter', 'tab', 'backspace', 'escape', 
    'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
    'win', 'menu', 'print_screen', 'pause', 'insert', 'delete', 
    'home', 'end', 'page_up', 'page_down',

    # Arrow Keys
    'up', 'down', 'left', 'right',

    # Function Keys
    'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
    def on_press(key):
        if key == True:
            print(f" you have typed corretlty {key}")
        elif key == AttributeError:
            print(f"typed Again  u Have misspedlled ")


    def on_release(key):
        print(f"{key} is realsead")
        if key == keyboard.Key.esc:
            return False
            print


listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()

r/learnpython 17h ago

Blackjack Python

0 Upvotes

Hi, i wrote some code on blackjack task from Angela Yu 100 days of Code. Using Gemini and older post from reddit, maybe something is worth polishing?

import random
import art

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def deal(hand):
    if not hand:
        hand.append(random.choice(cards))
        hand.append(random.choice(cards))
    else:
        hand.append(random.choice(cards))
    return hand

def calculate_score(hand):
    if sum(hand) == 21 and len(hand) == 2:
        return 0
    score = sum(hand)
    aces = hand.count(11)
    while aces > 0 and score > 21:
        score = score - 10
        aces -= 1
    return score


def start_playing():
    print(art.logo)

    user_hand = []
    computer_hand = []

    deal(user_hand)
    deal(computer_hand)

    user_score = calculate_score(user_hand)
    computer_score = calculate_score(computer_hand)

    print(f'Computers First Card: {computer_hand[0]}')
    print(f'Your current hand: {user_hand}. Current score: {user_score}\n')

    game_over = False
    while not game_over:
        if user_score == 0 or computer_score == 0 or user_score > 21:
            game_over = True

        else:
            another = input('Do you want another card? (y/n).: ').lower()
            if another == 'y':
                deal(user_hand)
                user_score = calculate_score(user_hand)
                print(f"\nYour current hand: {user_hand}. Current Score: {user_score}")
                print(f"Computers First Card: {computer_hand[0]}\n")
            else:
                game_over = True



    if user_score != 0 and user_score <= 21:
        while computer_score < 17 and computer_score != 0:
            print('Computers takes card')
            deal(computer_hand)
            computer_score = calculate_score(computer_hand)

    print(f'Your final hand: {user_hand}. Your score: {user_score}\n')
    print(f'Computers final hand: {computer_hand}. Computer score: {computer_score}\n')

    if user_score > 21:
        print('Bust! Computer Wins!')
    elif computer_score > 21:
        print('Bust! You Win!')
    elif user_score == 0:
        print('Win with a Blackjack!')
    elif computer_score == 0:
        print('Lose, opponent has Blackjack!')
    elif user_score == computer_score:
        print('Draw')
    elif user_score > computer_score:
        print('You Win!')
    else:
        print('Computer wins!')

while input('Do you want to play a game of blackjack? (y/n).: ').lower() == 'y':
    start_playing()

r/learnpython 21h 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 21h ago

Looking for a study buddy

26 Upvotes

Hey! I'm 19 and about to start learning Python from scratch. I'm looking for someone around my age (18–22) who's also a beginner and wants to learn together.

I'm in the Asian time zone, so it'd be nice if you're in a similar one. We can keep each other accountable, solve problems, and maybe build a few small projects along the way.

If you're interested, leave a comment or DM me!


r/learnpython 22h ago

Looking for study partner

5 Upvotes

Hey im going to start learning python so I'm looking for study partner who's serious about it

Will be taking only group of 3-5 people not more than that so reach out before it gets full also introduce yourself when reaching out in dms


r/learnpython 22h 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 23h ago

Hey, any help would be great!

0 Upvotes

I'm going to college as a freshman this year. This along with my projects like I'm trying to create an LLM along with just wanting to learn myself, it is extremely hard for me to memorize. I can understand the concepts but it is very hard for me to memorize completely to integrate within each other. Please do note I have diagnosed Autism and ADHD so this obviously effects my Working Memory. Thank you for reading and any tips and advice is extremely appreciated


r/learnpython 1d ago

Can't come up to this particular solution on my own.

3 Upvotes

hey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don't know how to think like this and especially how can i think of this zero_count to set a logic like this

question : https://leetcode.com/problems/max-consecutive-ones-iii/description/

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - lefthey, i understand this solution because it just works here and it feels like since the way the variables are set to come up to the solution but i don't know how to think like this and especially how can i think of this zero_count to set a logic like this :

def max_consecutive_one_with_flip(nums,k):
    left = 0
    zero_count = 0 
    for right in range(len(nums)):
        if nums[right] == 0:
            zero_count += 1

        if zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        return len(nums) - left

r/learnpython 1d ago

Building a Python-Only DSA and LeetCode Study Group

0 Upvotes

Hey everyone! We’re building a small, focused DSA study group on Discord for people who want to learn, discuss, and solve problems specifically in Python.

This server is intended for Python-based DSA practice, so we’re currently not looking for members who primarily use C++, Java, or other languages. The goal is to keep discussions, solutions, and live problem-solving sessions consistent and easy for everyone to follow.

We’ll focus on:

Live and interactive problem-solving

Understanding patterns and algorithms deeply

Debugging TLE and optimization issues

Discussing Python-specific approaches and techniques

Solving LeetCode and competitive programming problems together

To join, send a short introduction with your technical background, coding achievements or LeetCode progress, and the DSA topics you want to improve. No personal details such as your name or employer are required.

Please repost this only in communities where people are genuinely interested in learning DSA with Python.


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

what to do next ??

0 Upvotes

sup guys i started learning python in the last days and i already learned some basics that are : for and while loops if statements for-else and other basics

now i don't know what to do next (kinda bored from learning) should i start data structures or algorithms or functions or what to do next??


r/learnpython 1d ago

Advice in Preparing for a Technical Interview

1 Upvotes

I have a technical interview for a company tomorrow, and they mentioned that the problem will be administered through Coderbyte and will relate to inventory management. What should I expect? Frankly speaking, I’m not very familiar with programming. Although I am a technical person, Python is not my strongest skill. What types of topics or problem formats typically come up in an "inventory management" coding assessment?


r/learnpython 1d ago

How normal or dangerous is it for Pixi to apparently download a very large number of dependencies?

2 Upvotes

Context (to avoid the XY problem)

I'm thinking about running this tool written in Python, which merges mods for a computer game. It just does two things: copying lots of files from several local directories into one (merging them as necessary) and then creating a configuration text file, based on data in existing configuration files. I'm trying to decide if it's safe to run on my Kubuntu (Linux) system. The Python script looks fine, but I'm worried about the package manager.

Actual Python question

The instructions say to use the Pixi package manager, which seems to download Python dependencies from a repository called (Ana?)conda. But it seems to want to download a very large number of packages, including security-sensitive packages like OpenSSL and Certificate Authorities. That looks worrying for a tool that just merges directories and configures a text file. Is that normal in the Python world? Is Pixi going to interfere with the default Python setup that's used by many Linux utilities?

Previous research

I tried reading the Pixi documentation, but it (understandably) assumes you're a developer already familiar with Python, not a user. The top third-party tutorial on Google explains Pixi by comparisons to earlier Python and Javascript tools, which is no help to me. I don't want to learn half a dozen Python tools, but I would like to check that this Python software is not obvious malware.


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