如何从打印行上方的用户处获取输入?

2024-04-20 05:59:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在输入后直接打印,而不等待用户回答输入语句

def InputSaveName():
    try:
        import os, sys, time, pickle, colorama
    except Exception as e:
        print("Some modules are mssing! Install them and try again! {}".format(e))
    colorama.init()
    print("+----------------------+")
    print("What is your name adventurer?")
    name = input("> ")
    print("+----------------------+")

我希望在不等待用户在输入语句中添加内容的情况下打印底线。简而言之:我希望代码同时运行


Tags: 用户nameimporttimeosdefsysexception
3条回答

这可能就是你要找的。 有一个“后台进程”正在运行,同时使用两个单独的线程等待您的输入

import time
import threading

def myInput():
    print("Type your name when ready!")
    name = input()
    print("Your name is: ", name)

def backgroundProcess():
    while (True):
        print("Some code is running...")
        time.sleep(1)


inputThread = threading.Thread(target=myInput)
processThread = threading.Thread(target=backgroundProcess)

inputThread.start()
processThread.start()

这似乎是一个XY问题。您并不真正希望使用线程同时运行多行代码。要构建复杂的全屏终端应用程序,您应该看看^{}

import curses

def getname(stdscr):
    stdscr.clear()
    
    stdscr.addstr(0, 0, "+---------------------------+")
    stdscr.addstr(1, 0, "What is your name adventurer?")
    stdscr.addstr(2, 0, "> ")
    stdscr.addstr(3, 0, "+---------------------------+")
    
    curses.echo()
    return stdscr.getstr(2, 3, 20)

s = curses.wrapper(getname)
print("Name is", s)

这只要求输入名称,然后返回,但您也可以添加行,或替换现有屏幕上的现有行并刷新屏幕

由于可以访问标准输出,因此无法100%确定它是否适用于您在问题中键入的特定示例

如果您想并行运行,可以阅读关于线程/子进程https://docs.python.org/3/library/subprocess.html

或fork/多处理 https://docs.python.org/3/library/multiprocessing.html

在op编辑后编辑;-)

你想做的事情似乎与这个问题中描述的非常相似Python nonblocking console input

相关问题 更多 >