Remove prompt from console after user enters text with input() [duplicate] - python

This question already has answers here:
How to stop the input function from inserting a new line?
(9 answers)
Closed 4 years ago.
Is it possible to remove the prompt and the text that the user typed when using input()? I am using cmd on Windows 10 and would prefer a solution that works cross platform, but I don't really mind.
First attempt
Using the code:
user_input = input("Enter some text: ")
print("You just entered " + user_input)
produces:
Enter some text: hello
You just entered hello
but I would like:
Enter some text: hello
and then:
You just entered hello
Second attempt
I've used the getpass module, but that hides what the user is typing because it is designed for passwords. I looked at the code for getpass2 here and found that it uses the getch() function from msvcrt. I tried using a similar method, but it did not work. This code:
import msvcrt
prompt = "Enter some text: "
user_input = ""
print(prompt, end="\r")
current_character = ""
while current_character != "\r":
current_character = msvcrt.getch()
user_input += str(current_character, "utf8")
print(prompt + user_input, end="\r")
print("You entered" + user_input)
produces this output:
Enter some text: h e l l o
and then when I press enter:
nter some text: h e l l o
It also allows the user to use the backspace key to delete the prompt.
Third attempt
I know I can use os.system("cls") to clear everything in the console, but this removes text that was in the console before. For example, this code:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
removes the foo that was printed to the console before the input. If what I'm asking isn't directly possible, is there a workaround that can save the text in the console to a variable, and then after the user input clear the console and reprint the text that was in the console?

This is definitely not the optimal solution;
However, in response to
is there a workaround that can save the text in the console to a
variable
, you could keep appending the required text to a variable, and re-print that each time, as you suggested. Again, I would not recommend this as your actual implementation, but while we wait for someone to come along with the correct approach...
import os
to_print = ""
to_print += "foo" + "\n"
print(to_print)
user_input = input("Enter some text: ")
os.system("cls")
to_print += "You just entered " + user_input + "\n"
print(to_print)

Related

Getting my Python program to run Power Shell Script

Hello please forgive me if my question duplicate, I've searched previous questions and nothing seems to be quite the same. I'm working on a program that will scan a specific folder and search for specific file types to create a menu for a user to select. Once the user select the menu option the the corresponding file which is a power shell script. Currently My program does everything but run even a simple power shell script. I've attempted several configuration and it's not working. It would be great if someone can see what I may be doing wrong or provide me with some pointers. Code below.
##Text Menu Dynamic test
##version 1
## Created By Dragonshadow
## Code produce in Notpad++ For python v3.4.4
import os
import subprocess
import time
import pathlib
import logging
import fnmatch
import re
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir('C:\\Users\\myfolder\\Documents\\Automation_Scripts\\ENScripts\\'),"*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1)) + "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
def you_sure():
opt = input("Are you sure Yes or No: ")
if opt=="Yes":
print("Continuing please wait this may take a moment...")
elif opt=="No":
print("returnig to Enoc Menu")
else: ##Stays in loop
print ("Please choose yes or no")
##count_down
def count_down ():
count_down = 10
while (count_down >= 0):
print(count_down)
count_down -= 1
if count_down == 0:
print("Task will continue")
break
##initiating loop
loop = True
while loop:
choice = ENOC_menu()
print ("\n" +"You selected "+ choice +"\n")
subprocess.call("C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" + choice, shell=True)
##print ("---" +str(selectedFile))
You have probably already figured this out, but I the problem is in the subprocess.call() line. You are concatenating the powershell.exe path and the target file name together. See here:
>>> scriptToRun = "c:\\users\\Username\\Documents\\WindowsPowerShell\\classtestscript.ps1"
>>> powershellExe = "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
>>> print(powershellExe + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exec:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
Above, the two strings are stuck together without a space between them. Windows can't make sense of what you're trying to execute.
Put a space between the two two and subprocess.call() will understand what you're trying to do:
>>> print(powershellExe + ' ' + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exe c:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1

How to take any input from the users in capital letters even if the user is entering it in small letters?

I am trying to generate a story using python. For this I'm trying to take the input from the users for some questions. The scenario I'm trying to get is that whenever the user enters the input, then it is displayed on the output screen in capital letters.
But what happens is that the text is diplayed in small letters.
Here is the sample of the code
message1 = input(" my name is: ")
message2 = input(" i am from: ")
message3 = input(" i love to eat: ")
print( " My name is " + message1.upper() + " I am from " + message2.upper() + " I love to eat " + message3.upper())
I expect My name is SANDEEP when the user enters sandeep, but I get sandeep.
You can use this following code for console app. I am converting the input after reading it whole. But you can do the job quiet easily and get your desired result(Converting every character as you enter to uppercase) when you'll implement it in web applications( by using html and javascript there).
import os
message1 = input(" MY NAME IS: ")
os.system('cls')
message1="MY NAME IS : "+message1.upper()
res=message1+"\n"
message2 = input(res+"I AM FROM: ")
os.system('cls')
res+="I AM FROM : "+message2.upper()+"\n"
message2="I AM FROM : "+message2.upper()
message3 = input(res+"I LOVE TO EAT: ")
os.system('cls')
res+="I LOVE TO EAT : "+message3.upper()+"\n"
message3="I LOVE TO EAT: "+message3.upper()
print(res+"\n\n\n"+ message1 +"\t"+message2+"\t"+message3)
So, this will only work on Linux systems and only with ASCII characters:
import termios
import sys
def uppercase_input(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
old = termios.tcgetattr(sys.stdout.fileno())
new = old[:]
new[1] |= termios.OLCUC
termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, new)
try:
return input().upper()
finally:
termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, old)
result = uppercase_input("all uppercase? ")
print("yes: {}".format(result))
This uses some interesting ancient settings to convert I/O to/from uppercase from the old times when there were terminals only supporting upper-case ASCII.
From man tcsetattr:
OLCUC (not in POSIX) Map lowercase characters to uppercase on output.
So this solution is not really portable.
For a fully portable solution, you would need to implement echoing yourself.

Running code through iPython or command window by double clicking

When coding with Python, I've been using Spyder (as it came part of the package that I needed for work)
It comes with an editor, and of course a console, so I write my code and then run it there also.
It looks like this for those who are unfamiliar:
Here I can run my code no problem and get no errors.
Of course, I also save this code to a file, and I would like to get that code running by just double-clicking on the file name. Is that possible?
I can do it now and get a command prompt, but when I do it now I get this error:
(I'm using the same code that's in the images, can anyone tell me what I am doing wrong?
Here is my clear() code in case that matters:
def clear():
os.system(['clear','cls'][os.name =='nt'])
Edit:
Here's the last portion of the code, since the pictures are hard to read.
player = raw_input("What is your name? ")
The game itself
def hangman(player):
clear()
print "Hello! \nWelcome to Hangman, %s" % player
if init_play() == "quit":
print "Ok. Goodbye"
return
word = word_gen("text")
word_hidden = ["-" for x in range(0,len(word))]
av_letters = [chr(x) for x in range(97,123)]
guessed = []
turn = 1
print ("I am thinking of a word that is %d letters long\n" % len(word))
print "Here is the board\n"
print_board(word_hidden)
print "\nHere are your available letters:\n"
show_letters(av_letters)
while turn <= 5:
if word_hidden.count("-") == 0:
print "\nYou won!"
play_again()
print "\nGuess %d out of %d\n" % (turn, 5)
turner = word_hidden.count("-")
guess = raw_input("Guess a letter! ")
als = av_letters.count(guess)
guess_check(guess, guessed, word, word_hidden, turn, av_letters)
if als == 0:
pass
elif word_hidden.count(guess) == 0:
turn+=1
print ("You lose.\nThe word was %s\n" % word)
print ""
play_again()
clear()
hangman(player)
To use os.system, you need to import the os module first. The code is missing the import statement.
Put the following line at the beginning of the code:
import os

What do you have to type into Password to display Correct?

I am new to python, and a friend of mine has given me this code. I have searched up \b and \r and figured out that they're end-of-word character and return, respectively. However, I have typed it exactly as a is, even copied on text editor, but it still says hat I failed. So, how exactly is a supposed to be typed?
#!/usr/bin/env python
a = "password \b\b\b\b\b " + "\b\b\b " + "\b\r "
b = "123456789"
c = "qwertyuiooo"
d = "sdfghjkl;"
e = "zxcvbnm,."
b = raw_input("Password: ")
if b == a:
print("Correct")
else:
print "YOUR A FAILURE!!!"
As Martijn Pieters points out, most terminals won't send the \b character when you type backspace. So entering the password with the keyboard is not possible.
However, the keyboard is not your only option for entering data. You can also pipe in data from another file. Create a file which contains the password, \b and all:
file = open("thePassword.txt", "w")
file.write("password \b\b\b\b\b " + "\b\b\b " + "\b\r ")
file.close()
Then use < to pipe your password file into your friend's script.
C:\Users\AwesomeDude>myFriendsScript.py < thePassword.txt
Password: Correct

Python Application does nothing

This code stopped doing anything at all after I changed something that I no longer remember
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv()
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
edit: Lol sorry guys forgot to say its supposed to run the input
You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit'. Which is won't, because you are just using input(), not raw_input(), so the person would have to enter 'exit' (including quotes) or else the loop will never exit. (Assuming it's not Python 3 Code)
It's doing nothing because there's no code to make it do anything. Try inserting a line like
print("You entered:", userinput)
at an appropriate place in your loop.
os.getenv() must have at least one param. Try os.getenv("HOST") or something.

Categories

Resources