簡體   English   中英

如何在打印行上方獲取用戶的輸入?

[英]How can I take input from the user above a printed line?

如何在輸入后直接打印而無需等到用戶回答輸入語句?

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("+----------------------+")

我希望在不等待用戶在輸入語句中輸入內容的情況下打印底線。 簡而言之:我希望代碼同時運行。

這似乎是一個 XY 問題。 您真的不想使用線程來一次運行多行代碼。 要構建一個復雜的全屏終端應用程序,你應該看看curses

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 / multiprocessing https://docs.python.org/3/library/multiprocessing.html

在 op 的 EDIT 之后編輯 ;-)

你想要做的似乎與這個問題Python nonblocking console input 中描述的非常相似

這可能就是您要尋找的。 在使用兩個單獨的線程等待您的輸入時,有一個“后台進程”正在運行。

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()

您可以使用threading或多multiprocessing模塊:

import threading

def makeAsomethingOne():
    print('I am One!')

def makeAsomethingTwo(printedData=None):
    print('I am Two!',printedData)

name = input("> ")

firstThread = threading.Thread(target=makeAsomethingOne)
twiceThread = threading.Thread(target=makeAsomethingTwo,args=[name])

firstThread.start()
twiceThread.start()

這段代碼幾乎同時運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM