How to finish sys.stdin.readlines() input? - python

This might be a silly question, but as I can't find an answer, I have to ask it.
In interactive python I want to process a message which i get with:
>>> message = sys.stdin.readlines()
Everything works fine, but... how to stop it from getting an input and make it save into message variable? Stopping with ctrl+c stops whole process so there is no input to be saved anywhere. I guess there's an easy answer I just can't find...

For UNIX based systems (Linux, Mac):
Hello, you can type : Ctrld
Ctrld closes the standard input (stdin) by sending EOF.
Example :
>>> import sys
>>> message = sys.stdin.readlines()
Hello
World
My
Name
Is
James
Bond
# <ctrl-d> EOF sent
>>> print message
['Hello\n', 'World\n', 'My\n', 'Name\n', 'Is\n', 'James\n', 'Bond\n']
For Windows :
To send EOF on Windows, type Ctrlz

This is an old question but it needs an update about Windows and different keyboard layouts.
If neither CTRL + Z nor CTRL + D ** work for you on Windows and and you're wandering what is going on do this:
check if you are using default english keyboard layout
if you do have different, non-default keyboard layout try switching keyboard setting to English in language bar, then try pressing ctrl + z after changes
if you're still confused look at the screen, what appears in command line when you press ctrl + z. What symbol do you see? When I was pressing ctrl + z I was seeing this: ^Y, and when by mistake I pressed ctrl + y I've seen this ^Z, i pressed enter and the input was taken, EOF sent.
This is somewhat strange and counterintuitive. I changed keys layout some time ago to include polish characters, but all the common keys are left unchanged, z still maps to z when I use the keyboard normally, normally ctrl + z does nothing in my keyboard, so I shouldn't be changed. But apparently in cmd it works differently, in order to have default link between ctrl and z I have to switch to default layout, or use control y to sent EOF.

On windows simply do CTRL+Z and press enter

Use CTRL-D.
message = sys.stdin.readlines()
abc
def
<CTRL-D>
# message == ['abc\n', 'def\n']

If you are a Mac user, please use command + D. It works!

I tested that in VS code terminal.
After using this command:
for line in stdin:
I input many lines of data. Keep pressing Enter does not work now.
Solution:
Press Ctrl + Z, you will see ^Z in the terminal.
Then you have to press Enter to finish.

Related

Get user console input before user hitting enter

I have a quite simple problem.
I want to get some console input from a user (without an enter press at the end) and do something with it right away.
I quickly saw that the input() function from python would not work. I thought maybe you could write something like this:
sys.stdout.write("Input: ")
while True:
line = sys.stout.readline()
// Do something with the lines
But unfortunately it does not work because stdout is not readable. With stdin it does not work either because it waits for a enter press of the user.
Is it somehow possible to get lines without the user submit it?
You can get input from console interactively in byte format instead of getting a string with input command.
import sys
while True:
c = sys.stdin.read(1) # Read one byte
Here is what you might be looking for.
To get this working you will need to use pip install keyboard in the command line first.
import keyboard
while True:
key_pressed = keyboard.read_key()
print(f'You pressed {key_pressed}.')

Python: read from stdin with "for _ in sys.stdin" requires two Ctrl+Ds to exit?

This question is specific to Python 2.7. I'm using Linux. The question is about the following 3-line python program.
import sys
for line in sys.stdin:
print line
Question 1: When I run the program and type my input, why doesn't the program print anything when I press enter? It only prints after I press Ctrl+D.
Question 2: After I press Ctrl+D, why doesn't the program exit? Pressing Ctrl+D once prints all the stuff I typed so far (as mentioned in Question 1). I have to press Ctrl+D again to exit. I thought Ctrl+D was supposed to mark the end of file of sys.stdin? But apparently no: I can type a bunch of things, press Ctrl+D to print, type a bunch of things again, press Ctrl+D again, and so on.
Question 2 (extra): When I redirect a file into the program, as opposed to typing directly into the terminal, the program does terminate properly---that is, I don't need to "end the file twice" by pressing Ctrl+D twice. How come typing into the terminal is different?
Question 3: How come this program does work as expected in Python 3? (i.e. it echoes back what I typed in every time I press enter) What changed?
I anticipate that a good answer to this question would explain what is the iterator returned by sys.stdin in a for loop, and exactly what the iterator and the Python interpreter are doing. Other websites seem to vaguely point out that "for line in sys.stdin" reads the whole file before executing the for loop, but it doesn't explain why and how that works, why it doesn't work that way in Python 3, and why I need to press Ctrl+D twice on the terminal.

When using sys.stdin.read(), why I am not able to input from keyboard?

My code is as follows:
def function(a, b):
while a != 0 and b != 0:
...
return x
if __name__ == "__main__":
input = sys.stdin.read()
a, b = map(int, input.split())
print(function(a, b))
When I try to run it, the program doesn't give me a chance to input.
I get the following traceback message:
ValueError: not enough values to unpack (expected 2, got 0)
Can someone tell me the reason and how I can make input to test my program.
Thanks a lot.
sys.stdin.read() will read stdin until it hits EOF. Normally, this happens when that stream is closed by the other end (i.e. by whatever provides input).
This works if you run your program like cat inputfile.txt | your_program. But it will just keep reading endlessly in interactive mode when stdin is connected to your terminal, so the only way to close it from the other end is to close the terminal.
Strictly speaking, you can make read() stop by inputting a EOF character on a line by itself which is Ctrl-D in Unix and Ctrl-Z in Windows -- and this works in a regular Python console. But in IPython, this technique doesn't work: here in Windows, I see Ctrl-D as \x04 and Ctrl-Z as a blank line and neither stops the read (whether this is a bug or by design is another question).
So,
Use input() instead to input a single line, or
if you require multiple lines of input, use something that puts a limit on how much is read from stdin:
ll=[]
while True:
l = input() # or sys.stdin.readline().rstrip()
if not l: break
ll.append(l)
This way, you're able to stop the program from asking for more input by entering a blank line.
finally, there's sys.stdin.isatty() which allows you do invoke different code depending on whether the input is interactive (but for your task, this is probably an overkill).

Ctrl-C for quitting Python in Powershell now not working

Python fails to quit when using Ctrl-C in Powershell/Command Prompt, and instead gives out a "KeyboardInterrupt" string.
Recently I've reinstalled Windows 10. Before the reinstall Ctrl-C quit python (3.5/2.7) fine, with no output.
Does anyone know why this has started happening? Whether it's just a simple setting?
The only difference I can think of is I'm now on python 3.6. Ctrl-D works in Bash on Ubuntu on Windows, and Ctrl-C works fine in an activated anaconda python2 environment for quitting python.
I had this issue with Windows 10 Pro Build 18363 and Python 3.8.1. I was running some python scripts and was unable to stop some with CTRL + C, but CTRL + BREAK worked every time. The Windows Docs had this to say:
The CTRL+C and CTRL+BREAK key combinations receive special handling by console processes. By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input...
CTRL+BREAK is always treated as a signal, but an application can change the default CTRL+C behavior in two ways that prevent the handler functions from being called:
The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT input mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
When SetConsoleCtrlHandler is called with NULL and TRUE values for its parameters, the calling process ignores CTRL+C signals. Normal CTRL+C processing is restored by calling SetConsoleCtrlHandler with NULL and FALSE values. This attribute of ignoring or not ignoring CTRL+C signals is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.
Thus, CTRL + C seems to be a SIGINT and its actions can be modified by the program you are running. It seems that Python on Windows has been coded in such a way that CTRL + C is being processed as keyboard input rather than the SIGINT we are expecting. Fortunately for me I have the CTRL + BREAK keys on my keyboard and this works every time.
For those of you who dont have BREAK on your keyboard, you can use the Windows On Screen virtual Keyboard.
Press win key + r to open the run application program.
Type oskand press ok
On the virtual keyboard, press ctrl + ScrLk and this should kill the program.
This stack thread has some other methods you can try if ctrl + ScrLk doesnt work on the virtual keyboard.
You can type
CTRL + Z,
then hit ENTER to exit python from powershell.
Powershell Screenshot
This is a bug that recently appeared in Windows 10 Insider build 15002.
A work around is to change the Mapped Keys from Ctrl C to something like Ctrl K
If you are not familar how to do this, You can look up or at stty -a
You can run this command on each bash session that will map your Terminate to Ctrl + K
stty intr \^k
As a TEMP solution you could include this in your Bashrc so it is executed on each new session
This bug has been reported already on Github #1569
In my case, I found out that right ctrl + c does the trick in anaconda3 powershell - so no remapping necessary - I'm on Windows 10.
That worked like magic
If you have a laptop with Fn key, tap:
Ctrl + Fn + S
Source:
https://www.dell.com/community/Laptops-General-Read-Only/break-key-alternative/td-p/3826467
When you press Control C, a KeyboardInterrupt exception is thrown. If it isn't stopping the code, the best thing to do is to add a try statement into your code which catches KeyboardInterrupt
try:
....
except KeyboardInterrupt:
exit()
The code is just off the top of my head so sorry if something is wrong.
EDIT: Ctrl Break or on some keyboards Ctrl Pause instantly stops python code apparently.
Hitting Esc button on the upper corner of the keyboard seems to work for me on Windows-7, inside Spyder with numpy running, for Python 3.+
It broke the infinite ...: on an erroneous syntax in the interactive script
When I used to press Ctrl-C, python was quit normally without any output.
I really don't remember when I can quit python with Ctrl + C. In my memory, Ctrl + C always give me KeyboardInterrupt.
I also counldn't find an answer explaining why Ctrl + C can't quit the python in shell. FYI, Ctrl + D and Ctrl + \ can quit python for different reasons. See #Gilles's answer here. https://superuser.com/questions/169051/whats-the-difference-between-c-and-d-for-unix-mac-os-x-terminal
But I think how to handle Ctrl + C is merely a decision of the program. Yes, I think it totally depends on how the program would like to handle it. See the example I write below.
test.c
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static void ctrlC_Handler(int sig){
if(sig == SIGINT){
printf("(:KeyboardInterrupt:)\n");
printf(">>>");
signal(SIGINT, ctrlC_Handler);
}
}
static void welcome(){
printf("Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)\n");
printf("[GCC 7.3.0] on linux2\n");
printf("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n");
printf(">>>");
fflush(stdout);
}
int main(){
welcome();
signal(SIGINT, ctrlC_Handler);
for(;;){
pause();
}
return 0;
}
compile it with gcc test.c and execute it ./a.out. Try pressing Ctrl + C, you can see at least it mimics the behaviour(output) of the python program when you input Ctrl + C.
So, in my opinion, it's nothing special, but a human/programmer/author's decision on how to handle it.

Python, Press Any Key To Exit

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

Categories