Challenges with kbhit() in Python

I am currently working on a simple program that involves waiting for a specific amount of time before checking if a key has been pressed. Depending on the result, the program will execute different tasks later in the code. Here is the code snippet I have written:

import msvcrt
import time
import sys

time.sleep(1)
if msvcrt.kbhit():
    sys.stdout.write('y')
else:
    sys.stdout.write('n')

When I run the program and press any key at the beginning (triggering kbhit to be true), it always ends up executing the second statement and printing 'n'. Can anyone provide some guidance on what may be incorrect in my code?

{Using Python 2.7 and IDLE}

Thank you

Answer №1

Using the msvcrt.kbhit() function requires that the program is executed from the Windows command line, or if a console window is manually opened for input and output by double clicking on its respective .py file.

Running the program from IDLE or with the pythonw.exe interpreter will disconnect it from the console window, rendering the console-IO commands in the msvcrt module useless.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered: "Python unable to find module named http_client while attempting to execute Django alongside Django Rest Framework."

My goal is to develop a basic API using the django rest framework. The code in my view looks like this: from django.shortcuts import render from moviestash.models import Movie from moviestash.serializer import MovieSerializer from rest_framework impor ...

Unlock the power of multiprocessing with decorators

I am looking to design a decorator that allows a function to accept a single argument for handling iterable arguments in parallel. Here is the sample code: import functools import time from multiprocessing import Pool def parallel(func): def wrappe ...

A Python method for encoding "non-traditional" components of a URL using URL quoting

Below is the URL that I currently have: https://www.verizon.com/OnDemand/TVShows/TVShowDetails/Sr. Avila/1/9 I am looking to encode it in a way that makes it appear like a standard URL, while still remaining valid. For instance: https://www.verizon.com/ ...

A more Pythonic approach to managing JSON responses in Python 2.7

Currently, I am using Python 2.7 to fetch JSON data from an API. Here is the code snippet I have been working on: import urllib2 URL = "www.website.com/api/" response = urllib2.urlopen(URL) data = json.load(response) my_variable = data['location&apo ...

Ways to eliminate attributes from dataclasses

I am working with a dataclass that looks like this: @dataclass class Bla: arg1: Optional[int] = None arg2: Optional[str] = None arg3: Optional[Dict[str, str]] = None My objective is to achieve the following behavior: >>> bla = Bla(a ...

What are the various techniques available to insert an item into a list, and which one offers the quickest performance?

During a recent job interview, I was asked about Python: "How many methods are available to add an element to a list and which one is the most efficient?" I mentioned using the list's built-in methods like append, insert, and the use of the + operato ...

Looking to locate the succeeding word following a specific word in a text document?

Just joined this community! I'm on the hunt for the word that comes after "I" in a sentence. For example, in "I am new here" -> the next word is "am". import re word = 'i' with open('tedtalk.txt', 'r') as words: pat = re ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

How to access multiple cryptocurrency data using Binance's WebSocket API

Requesting assistance on fetching websocket data for multiple cryptocurrencies import websocket, json pairs = ['fxsusdt', 'bnbusdt', 'btcusdt'] socket = 'wss://stream.binance.com:9443/stream?streams=bnbusdt@kline_1m&a ...

Generating a moving average in a pivot table as time progresses

I am working on creating a pivot table with a rolling average over two days using the `pivot_table()` function in Python. Currently, I am using `aggfunc='mean'` to calculate the average rating for each day. However, I need to adjust the mean calc ...

Looking to automate the scraping of Wikipedia info boxes and displaying the data using Python for any Wikipedia page?

My current project involves automating the extraction and printing of infobox data from Wikipedia pages. For example, I am currently working on scraping the Star Trek Wikipedia page (https://en.wikipedia.org/wiki/Star_Trek) to extract the infobox section d ...

Python code: Attempting to retrieve the hour, minute, and second values from a datetime object

As a newcomer to the Python environment, I am working on manipulating datetime objects by using the method replace(hour=...,minute=...,second=...) in an iterative manner and storing the results at each step in a pd.Series. The objective is to have a pd.Ser ...

Access denied for user: MySQL encountered an ERROR 1045 (28000) which prevented the user

My attempt to connect a readonly MySQL-DB to my Django WebAPP has encountered a persistent error. Whether using Django, MySQL-Workbench, or MySQL-Shell, the outcome remains constant: ERROR 1045 (28000): Access denied for user 'db-foo-read'@' ...

Mastering the art of efficiently capturing syntax errors using coroutines in Python

Currently, I am in the process of developing a Python script that runs two tasks simultaneously. Transitioning from JavaScript to Python's async/await coroutine features has presented some challenges for me as I have encountered unexpected behavior. ...

Need help with redirecting after a form post using the scrapy_splash package?

I am working with Python, Scrapy, Splash, and the scrapy_splash package to extract data from a website. After successfully logging in using the SplashRequest object in scrapy_splash, I obtain a cookie that grants me access to a portal page. Everything has ...

I require assistance merging strings that include numerical values

As I begin my scripting course today, I am faced with the challenge of combining strings that contain numbers without actually adding them together in Python. I understand that number1 + number2 will add the numbers, but I am unsure how to simply combine ...

Tips for transforming gridded temperature data in CSV format (organized by latitude and longitude) into a raster map

Recently, I acquired a dataset that shows the average temperature change across the entire US, but it is formatted with lat/long range. The original csv file can be found here: original csv I am attempting to convert this data into a raster for visualizat ...

What is the proper way to store strings in variables within Python, and subsequently access and utilize those variables in various functions or methods within the

Recently, I encountered a straightforward issue regarding printing emojis in Python. After some research, I discovered three main methods to achieve this: Using UNICODE representation of the emoji Using CLDR names of the emoji Utilizing the emoji module ...

SQLAlchemy - restricting the joined-loaded results

Database Structure: class Team(Base): id = Column(Integer, primary_key=True) name = Column(String, nullable=False) players = relationship("Player", backref="team") class Player(Base): id = Column(Integer, primary_key=T ...

Point is not clickable - utilizing SELENIUM with PYTHON

How can I expand the arrow as shown in the image below from https://i.stack.imgur.com/tFqGY.png This is the code snippet I am using: from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from s ...