I am a complete beginner in python as well as this website.
Background:
I have tried to program a random password generator that allows the user to input the length of the password and how many passwords the user wants.
Everything works perfectly fine when I run the program in pharm. So I converted the script into .exe file. It does not crash instantly, it stills allow the user to input values but once the user entered the values in, it crashes.
I tried using pyinstaller from youtube tutorials to "properly" convert the script into .exe, but the same result still occurs. (Previously, I simply copy and paste my script into notepad and name that notepad in terms of .py and run it.)
Here are my codes:
import random
import sys
chars = "abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789!##$%^&*+="
try:
length_password = int(input("Enter the length of your password: "))
how_many = int(input("Enter how many passwords you want: "))
except:
print("Invalid input (numbers only!)")
sys.exit()
def length_function(length):
password = ""
for number_times in range(0, length_password):
password = password + random.choice(chars)
return password
print("Here are your passwords: ")
number_times1 = 1
while number_times1 <= how_many:
print(length_function(length_password))
number_times1 = number_times1 + 1
Like I mentioned before, it runs well in pycharm but not in a .exe file.
I've seen your other question and try to explain more on the solution for this problem:
When running a code, program, or whatever, that code might end somewhere, where nothing has to be done anymore.
That's the point where your operating system (Windows, Linux etc) just exits the program. What you might expect is that the console stays open so you can read the ouput, right?
So why does this often work but often doesn't?
When calling your code from an already existing command window (for e.g. cmd.exe), the console (which is a program itself) is not finished and won't close after runnning your program. That's the point where you can read the printed output from you own program.
When you call your program from somewhere else, it is opening a console just for that purpose and it's configured in that way, that it doesn't stay open after executing your program. So when your code is executed, it prints something on the console; but immediately after its done and the console closes, too.
That is where the solution input("Press Enter to exit") comes into play. input() is a function which waits for user input; so it's waiting infinitely for you to hit enter. That means, your program is not finished. That gives you the time you read the output you want to read.
When I use raw_input, the prompt only shows after the user gives input. Like this:
number = raw_input("Enter a number:")
but when I run this, nothing happens, the I type a number, the it shows the prompt:
123
Enter a number:
(123 used to be blank until I typed a number and hit enter)
I just want the prompt to display before the user input. If anybody knows how to fix this please help.
Thanks.
You might be in an environment where your standard output is buffered and won't flush until there is a newline character.
You can take advantage of the fact the standard error is unbuffered and redirect standard output to standard error instead:
import sys
sys.stdout = sys.stderr
Thanks for you suggestion, and I did try that, but unfortunately it didn't work, but I did find the solution:
I had to add
sys.stdout.flush()
before each time I had a
variable = raw_input("A prompt")
to flush the buffer.
Although for the first
raw_input("A prompt")
it will not work work unless you already printed something, for example
variable = raw_input("A prompt")
sys.stdout.flush()
would still have the same issue, whereas
print"Welcome,"
variable = raw_input("A prompt")
sys.stdout.flush()
would work.
I try to read from windows console utf-8 letters.
I have the code follows:
import codecs
sys.stdin = codecs.getreader('utf-8')(sys.stdin)
if __name__ == '__main__':
print 'query=',
query = sys.stdin.readline()
print query
But there is a strange thing:
After pressing the enter button the execution of the stdin.readline() or raw_input() or input() functions will not stop.
What do I do wrong? Or how to send eof() to stop input from console in this case?
On my Mac, hitting ^D (Ctrl-D) twice does the trick. Not sure if this will work across systems, but give it a shot.
So, as the title says, I want a proper code to close my python script.
So far, I've used input('Press Any Key To Exit'), but what that does, is generate a error.
I would like a code that just closes your script without using a error.
Does anyone have a idea? Google gives me the input option, but I don't want that
It closes using this error:
Traceback (most recent call last):
File "C:/Python27/test", line 1, in <module>
input('Press Any Key To Exit')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
If you are on windows then the cmd pause command should work, although it reads 'press any key to continue'
import os
os.system('pause')
The linux alternative is read, a good description can be found here
This syntax error is caused by using input on Python 2, which will try to eval whatever is typed in at the terminal prompt. If you've pressed enter then Python will essentially try to eval an empty string, eval(""), which causes a SyntaxError instead of the usual NameError.
If you're happy for "any" key to be the enter key, then you can simply swap it out for raw_input instead:
raw_input("Press Enter to continue")
Note that on Python 3 raw_input was renamed to input.
For users finding this question in search, who really want to be able to press any key to exit a prompt and not be restricted to using enter, you may consider to use a 3rd-party library for a cross-platform solution. I recommend the helper library readchar which can be installed with pip install readchar. It works on Linux, macOS, and Windows and on either Python 2 or Python 3.
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()
msvrct - built-in Python module solution (windows)
I would discourage platform specific functions in Python if you can avoid them, but you could use the built-in msvcrt module.
>>> from msvcrt import getch
>>>
>>>
... print("Press any key to continue...")
... _ = getch()
... exit()
A little late to the game, but I wrote a library a couple years ago to do exactly this. It exposes both a pause() function with a customizable message and the more general, cross-platform getch() function inspired by this answer.
Install with pip install py-getch, and use it like this:
from getch import pause
pause()
This prints 'Press any key to continue . . .' by default. Provide a custom message with:
pause('Press Any Key To Exit.')
For convenience, it also comes with a variant that calls sys.exit(status) in a single step:
pause_exit(0, 'Press Any Key To Exit.')
Check it out.
a = input('Press a key to exit')
if a:
exit(0)
Here's a way to end by pressing any key on *nix, without displaying the key and without pressing return. (Credit for the general method goes to Python read a single character from the user.) From poking around SO, it seems like you could use the msvcrt module to duplicate this functionality on Windows, but I don't have it installed anywhere to test. Over-commented to explain what's going on...
import sys, termios, tty
stdinFileDesc = sys.stdin.fileno() #store stdin's file descriptor
oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc) #save stdin's tty attributes so I can reset it later
try:
print 'Press any key to exit...'
tty.setraw(stdinFileDesc) #set the input mode of stdin so that it gets added to char by char rather than line by line
sys.stdin.read(1) #read 1 byte from stdin (indicating that a key has been pressed)
finally:
termios.tcsetattr(stdinFileDesc, termios.TCSADRAIN, oldStdinTtyAttr) #reset stdin to its normal behavior
print 'Goodbye!'
Ok I am on Linux Mint 17.1 "Rebecca" and I seem to have figured it out, As you may know Linux Mint comes with Python installed, you cannot update it nor can you install another version on top of it. I've found out that the python that comes preinstalled in Linux Mint is version 2.7.6, so the following will for sure work on version 2.7.6. If you add raw_input('Press any key to exit') it will not display any error codes but it will tell you that the program exited with code 0. For example this is my first program. MyFirstProgram. Keep in mind it is my first program and I know that it sucks but it is a good example of how to use "Press any key to Exit"
BTW This is also my first post on this website so sorry if I formatted it wrong.
in Windows:
if msvcrt.kbhit():
if msvcrt.getch() == b'q':
exit()
In python 3:
while True:
#runtime..
answer = input("ENTER something to quit: ")
if answer:
break
You can use this code:
from os import system as console
console("#echo off&cls")
#Your main code code
print("Press Any Key To Exit")
console("pause>NUL&exit")
I have a simple Python program which uses a read-eval-print loop to read user input via raw_input and then print things to the screen. I would like to keep a history of previous inputs and cycle through them when the user presses keyup or keydown, similar to the Python interpreter or to the bash shell. How can I do this in Python?
Someone asked for sample code:
while True:
user_input = raw_input()
print user_input + " this many hats!!!"
I'd like to make it so a keyup puts the last line of input on the command line. The first answer given, use the readline module, is likely the best.
Try using the readline module. If your platform supports readline, simply importing the module should make its functionality available via the raw_input prompt.
For standard input function also works. No configuration needed. Just import readline.