Domanda

Can I change where the raw_input cursor is when the program is running?

For example, my code is:

print raw_input ("Please enter your last name..")
print ("                                        Type now ..")
print raw_input ("please enter your first name..")

I want the "Type now" part to be in the lower part of the screen somewhere but the flashing | to remain after the "please enter your last name" part.

Oooo, while I am here, can someone paste me out the code that makes my | spin around? :D or impress me with something even more fancy?

È stato utile?

Soluzione

There is no cross-platorm way to do this kind of "console GUI" functionality.

If you don't care about Windows, most other platforms have the curses module. It's a bit heavy-weight for what you want, but it can do everything you want and more.

Alternatively, if you only care about common terminals (ANSI control sequences, 80-character width, etc.), you can do it by sending explicit control sequences, or using wrapper libraries that do so on your behalf.

Or, if you only care about Windows, there are various different wrappers around conio on PyPI.


And as you may have guessed, the code to spin the cursor around depends on which library you used. Although you don't actually need full cursor movement functionality for that; you just need some way to read from the keyboard in raw mode. (You can do this on Windows with the msvcrt library, on Unix with the tty library and/or just using select on stdin.) Then, you just loop, waiting for a key with a timeout of, say, 0.1 seconds, and update the cursor if it times out.

Something like this:

cursor = itertools.repeat(r'|/-\')
while True:
    if msvcrt.khbit():
        return msvcrt.getwch()
    msvcrt.putwch('\008')
    msvcrt.putwch(next(cursor))
    time.sleep(0.1)

Altri suggerimenti

while True:
for i in ["/","-","|","\","|"]:
print "%s\r" % i,

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top