0

I want to clear the line of text created after the input() function. I've tried \033[a, \r, end='' but either I'm doing it wrong or it doesn't work. Is there a better way:

Code is:

rawguess = input('Enter a 5 letter word: ')
print('words go here')

I've tried:

rawguess = input('\033[A' + 'Enter a 5 letter word: ' + '\033[A')
print('words go here')
rawguess = input('Enter a 5 letter word: ')
print('\rwords go here')
rawguess = input('Enter a 5 letter word: ')
print('\r', end='')
print('words go here')

And other variations of these three but nothing's worked so far.

7
  • Hello @spuddo, and welcome to StackOverflow! I think, because input prints a newline, you need to move the cursor up 1 line after input, instead of in the input prompt text. Commented Aug 13, 2022 at 8:14
  • Does this (stackoverflow.com/questions/517970/…) or this (stackoverflow.com/questions/44565704/…) answer your question? It clears everything in the console though. Commented Aug 13, 2022 at 8:16
  • What operating system are you using? Commented Aug 13, 2022 at 8:27
  • @JoboFernandez Tried a bunch of those, they either cleared the whole console or didn't do anything :/ Thanks for the reply though Commented Aug 13, 2022 at 8:30
  • @Bharel Windows 10 Commented Aug 13, 2022 at 8:31

2 Answers 2

1

I didn't know this before, but apparently Windows now supports Console Virtual Terminal Sequences, which include using ESC [ <n> A to move the cursor up (like on *nix). So we can call the Win32 API with ctypes.windll and enable Virtual Terminal Sequences, which will allow us to use '\x1b[1A'.

import sys

# Only do this on Windows, so that *nix users
# can also run the program without errors
if sys.platform.startswith('win'):
    import ctypes
    from ctypes.wintypes import *

    STD_OUTPUT_HANDLE = -11
    ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

    kernel32 = ctypes.windll.kernel32

    h = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    m = DWORD()
    kernel32.GetConsoleMode(h, ctypes.pointer(m))
    m.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
    kernel32.SetConsoleMode(h, m)

rawguess = input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here')
Sign up to request clarification or add additional context in comments.

Comments

1

Well I just found a piece of dark magic allowing you to enable terminal controls in Python:

import subprocess
subprocess.run("", shell=True)
input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here       ')

1 Comment

Thanks for the trick! However, I would not rely on this feature because AFAIK it's not documented anywhere... The Win32 API is documented and should work with all implementations of Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.