Reputation: 124
How can I print directly after my input without waiting until the user answered the input statement?
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("+----------------------+")
I want the bottom line to print without waiting for the user to put something in the input statement. In short: I want the code to run simultaneously.
Upvotes: 0
Views: 142
Reputation: 82949
This seems to be an XY problem. You do not really want to use threading to run multiple lines of code at once. To build a complex full-screen terminal application, you should have a look at 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)
This only asks for the name and then returns, but you can also add lines, or replace existing lines on the existing screen and refresh the screen.
Upvotes: 4
Reputation: 1060
This might be what you are looking for. There is a "background process" running while waiting for your input using two separate threads.
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()
Upvotes: 0
Reputation: 17
You can use threading
or multiprocessing
modules:
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()
This code runs almost simultaneously.
Upvotes: -1
Reputation: 7541
Without being 100% sure if it works in the specific examples you have typed in your question because of access to the standard output.
If you want to run things in parallel you can read about threads / subprocess https://docs.python.org/3/library/subprocess.html
or fork / multiprocessing https://docs.python.org/3/library/multiprocessing.html
EDIT after op's EDIT ;-)
What you want to do seems very similar to what's described in this question Python nonblocking console input
Upvotes: 0