Input problems in cmd - python

I'm having a problem where if I run my python program in the windows terminal, text with inserted variables (%s) have wacky results, where as in the python shell it works fine.
Code:
print("Hi! What's your name?")
name = input("name: ")
print("Nice to meet you %s" % name)
print("%s is a good name." % name)
print("This line is only to test %s in the middle of the text." % name)
input("press enter to exit")
Result in python shell:
Result in cmd:
I'm using Windows 10 and python32 in case you needed to know.

This is a bug in the original 3.2.0 on Windows. The input() statement stripped off the "\n" but not the '\r', so the string input is hidden.
See https://bugs.python.org/issue11272
Quick fix:
name = input("name: ").rstrip()
It was fixed in 3.2.1. You really should upgrade your Python!

Related

Prevent python from showing the user's typed input line after he types it (He should be able to see what he is typing) [duplicate]

This question already has answers here:
Type text without displaying text
(2 answers)
Closed 1 year ago.
In python is it possible to erase the user's input line?
For example:
msg = input("")
print("User: "+msg)
Output (Of the comp) :
Hey
User: Hey
Output (I want) :
User: Hey
There is an another question quite similar to this but it doesn't work for me.....
Prevent Python from showing entered input
Update:
A few details, I want to check the Users input before printing it, I even have a thread running in the same file that prints statements at random intervals. (This code is actually part of a video game chat)
Just write:
print("User: "+ input(""))
Update:
if you want to store the input so just do this:
print("User: ", end='')
msg = input("")
the print() function puts "\n" at the end of the string, so by replacing "\n" with "" we prevent python to jump to the next line and the user could write after printed text, "User: ".
Update 2:
you can build a user interface for your program and it makes your work so easy. However, if you want to run your program on the console, the easiest way is to store all the printed strings in the console then clear the console each time the user inputs a msg and then print stored strings. Now you have the msg which is not printed in the console, so you can do whatever you want with it and then print it as print('User: ' , msg).
to clear the console:
import os
clear = os.system('cls') #for Windows
clear = os.system('clear') #for Linux
You can write clear like clear = lambda: os.system('cls') and use it like clear() whenever you want. But it return 0 and print a '0' in your console.
a full example:
import os
def clear():
dummy_var = os.system('cls')
stored_string = [f'stored {i}' for i in range(10)]
for txt in stored_string:
print(txt)
msg = input("")
clear()
for txt in stored_string:
print(txt)
print('User: ', msg)
stored_string.append('User: ' + msg)
run this example and see the result.

How to correctly configure the use of python 3 to avoid NameError: name '' is not defined

I was trying a very simple code on my MacBook: here is the code
def file_name(fname):
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
count = 0
starts_with = **input**('Entries starts with: ')
for line in fhand:
if line.startswith(starts_with):
count = count + 1
print('There were ', count, ' subject lines in', fname)
fname = input('Enter the file name: ')
file_name(fname)
In order for that code to work, I had to replace input() with raw_input(). I have installed python 3.8 on my device though cannot run the code with it. At first, I thought the problem was with VS code. After switching to PyCharm professional I still have the same, exact problem.
The desired output after renaming to raw_input() is:
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Entries starts with: print
('There were ', 1, ' subject lines in', 'hw.py')
Output when using input()
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Traceback (most recent call last):
File "File.py", line 15, in <module>
fname = input('Enter the file name: ')
File "<string>", line 1, in <module>
NameError: name 'hw' is not defined
My configuration for PyCharm:
PyCharm, click to view screenshot
for VS code:
VS code, click to view screenshot
What should I do to yield the desired result?
UPDATE: I dug around and found this solution from Ryosuke Hujisawa (second upvoted answer) worked for me: how to change default python version?
Now my default version of python has been changed to python 3.
When running that code, you still need to state you want python3 to IDE but doing so you won't need use raw_input() from python 2 anymore for the code to work.
Your IDE doesn't control your terminal session. python -V will show you what the problem is, or more precise, the version you're executing the script with
You should try to run /usr/bin/python3 hw.py, for example for python 3.7.3 or with /usr/local/bin/python3 for 3.8.3
Or you need to activate your venv then you can just use python
Are you sure that you are running it on python 3.In python 3 there is no raw_input()
It should work with input() if you use python3 File.py.

How can I prevent Spyder from inserting a new line after taking user input?

Spyder inserts a blank line in the console output between every call of the input() function but I don't want that (i.e. I want the input() prompts to be on contiguous lines in the console instead of separated by a blank line). Is there a way to do that? I tried using input("foo", end="") thinking it may work like the print() function but that's not the case...
Code:
fname = input("Please enter your first name: ")
lname = input("Please enter your last name: ")
print("Pleased to meet you, " + str(fname) + " " + str(lname) + "!")
Output:
Please enter your first name: Jane
Please enter your last name: Doe
Pleased to meet you, Jane Doe!
Desired output:
Please enter your first name: Jane
Please enter your last name: Doe
Pleased to meet you, Jane Doe!
Edit:
As others have pointed out in the comments section, this issue is non-reproducible, even for me, except through the use of the IPython interface within the Spyder IDE. If anyone is running IPython outside of Spyder, please run the above code and let me know whether that produces the same output. I can reproduce the undesired output through Spyder's IPython interface but not through a Terminal session so this is something specific to either IPython or Spyder.
(Spyder developer here) This looks like a minor bug in our IPython console. Please report it here:
https://github.com/jupyter/qtconsole
Note: This console is not simply embedding a terminal IPython session in Spyder (that's why making comparisons to it make no sense at all).
Instead, it is a re-implementation of most of the terminal behavior but using a graphical toolkit (called Qt) and the Jupyter kernel/frontend architecture.
Perhaps not exactly what you're after, but it should solve your problem.
Delete previous line in console with:
def delete_previous_line():
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
fname = input("Please enter your first name: ")
delete_previous_line()
lname = input("Please enter your last name: ")
print("Pleased to meet you, " + str(fname) + " " + str(lname) + "!")
See remote last STDOUT.
If it doesn't work try
print(CURSOR_UP_ONE + ERASE_LINE)
instead of
print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
No extra empty lines in Window Vista console.
Extra empty lines are inserted in Spyder when "execute in current console" is choosen.
These extra lines are NOT inserted if program is executed in "dedicated console". (Python 3.6, Spyder 3.2.3, IPython 5.3.0)
Spyder -> Run -> Configuration per file... -> Execute in dedicated console
(2017/10/16, 32-bit Anaconda on MS Windows Vista 32 bit.)

Comma does not separate lines of print in python34 on windows8?

I am learning python34 and I read here in my course book the following line:
"The comma separating the two print() commands in this file instructs Python to no start a new
line."
I am guessing by "no" they actually mean not?
Using the next script:
#!/usr/bin/env python3
print ("Hello from a Python file!"),
print ("Welcome to Python!")
And I have the following example of its execution on mac:
$ python3 ~/Desktop/Python/Hello.py
Hello from a Python file! Welcome to Python!
But my windows8 gives me this output:
c:\f>a.py
Hello from a Python file!
Welcome to Python!
I am running the file via cmd without the Python command (as shown above), since it doesn't work otherwise...
I added manually the system Environment Variables path to Python default installation
folder (C:\Python34)
The comma doesn't work in Python3, see what's new in Python 3. Also see the docs for print function in Python 3.
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
Your example would be:
>>> def test():
... print("Hello from a Python file!", end=" ")
... print("Welcome to Python!")
...
>>> test()
Hello from a Python file! Welcome to Python!
Output in Python3
Hello from a Python file!
Welcome to Python!
Output in Python2
Hello from a Python file! Welcome to Python!
This is because the comma notation has been removed as print has been made a function in 3 whereas it was a keyword in 2.
You can achieve what you want by using
print ("Hello from a Python file!",end = ' ')
print ("Welcome to Python!")
This making use of keyword arguments of the print function in python3

exercise 14 learning python the hard way

Here is the code from the exercise:
from sys import argv
script, user_name = argv
prompt = '> '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you like me %s?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
Now I am running Windows 7 and I am running the CMD line with the code
python ex14.py myname
I get this error:
File "ex14.py", line 3
Python ex14.py, user_name
SyntaxError: invalid syntax
There is nothing wrong with the script among visible characters.
check there is no Unicode whitespace in the source e.g., NO-BREAK SPACE character. Create a new script in the same directory:
with open('ex14.py', 'rb') as file:
s = file.read()
print(repr(s)[:60])
u = s.decode('ascii') # this line should raise an error
# if there are bytes outside ascii
check Python version to make sure it is 2.7 (to interpret correctly error messages):
$ python -V
check that the file is not saved using utf-16/32 encodings (#abarnert's suggestion in the comments).
You should see many zero bytes '\x00' in the repr() results in this case.
install python2 and in terminal type
python2 ex14.py myname
will solve the problem
you are running the script in the latest python version
and the syntax of your code is for python version 2
that's why you are getting the syntax error

Categories