So, took your code out of the function and ran some tests.
import sys
buffer = []
while run:
line = sys.stdin.readline().rstrip('\n')
if line == 'quit':
run = False
else:
buffer.append(line)
print buffer
Changes:
- Removed the 'for' loop
- Using 'readline' instead of 'readlines'
- strip'd out the '\n' after input, so all processing afterwards is much easier.
Another way:
import sys
buffer = []
while True:
line = sys.stdin.readline().rstrip('\n')
if line == 'quit':
break
else:
buffer.append(line)
print buffer
Takes out the 'run' variable, as it is not really needed.
Answer from Wing Tang Wong on Stack OverflowSo, took your code out of the function and ran some tests.
import sys
buffer = []
while run:
line = sys.stdin.readline().rstrip('\n')
if line == 'quit':
run = False
else:
buffer.append(line)
print buffer
Changes:
- Removed the 'for' loop
- Using 'readline' instead of 'readlines'
- strip'd out the '\n' after input, so all processing afterwards is much easier.
Another way:
import sys
buffer = []
while True:
line = sys.stdin.readline().rstrip('\n')
if line == 'quit':
break
else:
buffer.append(line)
print buffer
Takes out the 'run' variable, as it is not really needed.
I'd use itertools.takewhile for this:
import sys
import itertools
print list(itertools.takewhile(lambda x: x.strip() != 'quit', sys.stdin))
Another way to do this would be to use the 2-argument iter form:
print list(iter(raw_input,'quit'))
This has the advantage that raw_input takes care of all of the line-buffering issues and it will strip the newlines for you already -- But it will loop until you run out of memory if the user forgets to add a quit to the script.
Both of these pass the test:
python test.py <<EOF
foo
bar
baz
quit
cat
dog
cow
EOF
How to read line by line from stdin in python - Stack Overflow
python 3.x - Python3 : Using input() how to Read Multiple Lines from pipe (stdin)? - Stack Overflow
python - How do I read from stdin? - Stack Overflow
Using sys.stdin.readline() to read multiple lines from cmd in Python - Stack Overflow
I recently took a coding assessment where I was tasked to compute the square of the input which is relatively easy. The issue was that the input was a multiple line input:
7
16
and the expected output is
49
256
The given code was
for line in sys.stdin:
# your code here
print(line, end="")I tried to do ls = list(line.split()) but ls[0] is
['7']
['16']
and ls[1] is None
I also tried ls = list(line.split('\n')) but ls is
['7', '']
['16', '']
So how was I supposed to process the input to get ['7', '16'] rather than a 2 dimensional list?
From there I know how continue with make it an integer using map, creating a for loop for each item of the list and printing the square of each item.
I dont have a picture of the question since I was monitored on webcam but this is roughly what I remembered from the question.
edit: It was an online assessment platform so I am not sure exactly how the input was written as (like the raw input). Also I can only modify the code inside for line in sys.stdin:
Also, does anyone know how to write the input for sys.stdin using jupyternotebook such that I can practice this problem?
It's simpler:
for line in sys.stdin:
chrCounter += len(line)
The file-like object sys.stdin is automatically iterated over line by line; if you call .readline() on it, you only read the first line (and iterate over that character-by-character); if you call read(), then you'll read the entire input into a single string and iterate over that character-by.character.
The answer from Tim Pietzcker is IMHO the correct one. There are 2 similar ways of doing this. Using:
for line in sys.stdin:
and
for line in sys.stdin.readlines():
The second option is closer to your original code. The difference between these two options is made clear by using e.g. the following modification of the for-loop body and using keyboard for input:
for line in sys.stdin.readlines():
line_len = len(line)
print('Last line was', line_len, 'chars long.')
chrCounter += len(line)
If you use the first option (for line in sys.stdin:), then the lines are processed right after you hit enter.
If you use the second option (for line in sys.stdin.readlines():), then the whole file is first read, split into lines and only then they are processed.
Use the fileinput module:
import fileinput
for line in fileinput.input():
pass
fileinput will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.
Note: line will contain a trailing newline; to remove it use line.rstrip().
There's a few ways to do it.
sys.stdinis a file-like object on which you can call functionsreadorreadlinesif you want to read everything or you want to read everything and split it by newline automatically. (You need toimport sysfor this to work.)If you want to prompt the user for input, you can use
raw_inputin Python 2.X, and justinputin Python 3.If you actually just want to read command-line options, you can access them via the sys.argv list.
You will probably find this Wikibook article on I/O in Python to be a useful reference as well.
The solution to this problem depends on the OS you're using.
Basically, if you want multiline input, you'll have to use sys.stdin.read() instead of sys.stdin.readline(). Since sys.stdin is a file-like object in Python, the read() method will read until it reaches the end of a file. It is marked by a special character EOF (end-of-file). On different OS'es there is a different way of sending it.
On Windows:
Press Ctrl+Z after your input and then press Enter:
2 10
20 2
30 3
^Z
On a Unix-based OS:
Press Ctrl+D after your input. No Enter is required (I believe)
If you want to get a list [2, 10, 20, 2, 30, 3] from your input, you're fine. The split() method splits by whitespace (spaces, newlines, etc.).
I agree with everything @Leva7 has said. Nonetheless, I'd suggest another solution, which is to use raw_input for Python 2 or input for Python 3 like so:
args = []
s = raw_input() # input() for Python 3
while s != '':
args.extend([int(arg) for arg in s.strip().split()])
s = raw_input()
Of course, that's not a one-liner in any way, but it does the job and it's easy to see how it's done. Plus, no special characters are required at the end of the input.
So I'm trying to get into regular programming practice. Spent some time doing challenges at CodeEval and the likes with C++ a little ways back, but now that I'm coming back I want to focus a little on Python.
The problem is, I can't figure out how to read the multiple line input test cases for my first program. In C++ it was easy with a while/get loop, but I'm struggling to figure it out in Python. It's frustrating because I know its simple and I've done it before, but I can't for the life of me figure out this simple problem that is holding me back from solving the bigger tasks.
So the test case for example would be:
SetCol 32 10
SetRow 20 4
QueryRow 10
etc, and I need to run my functions on each line of input.
Any advice as the best way to do this would be appreciated, so I can get back to practicing!
What have you tried, and what form does the input take? If it's typed in, maybe you want something like this:
lines = []
line = input('First line: ')
while line:
lines.append(line)
line = input('Next line: ')
print(lines)
If you get the input from some source all at once, you can use
the_input.split('\n')
def parse():
n1, x1, y1 = raw_input().split(" ")
n2, x2, y2 = raw_input().split(" ")
n3, x3, y3 = raw_input().split(" ")
return [(n1,x1,y1), (n2,...)..]
inputs = [parse() for _ in range(len(tests)/3)]
in case you don't know how many tests are you need to read the whole input first:
import sys
lines = sys.stdin.readlines()
def parse(i):
n1, x1, y1 = lines[i].split(" ")
n2, x2, y2 = lines[i+1].split(" ")
n3, x3, y3 = lines[i+2].split(" ")
return [(n1,x1,y1), (n2,...)..]
inputs = [parse(i) for i in range(len(lines)/3)]
I'm trying to feed a prompt to a GPT-2 model, which is trained on song lyrics. With this model, you can feed it a prompt and it will attempt to finish it. The problem I'm having is that I need for the prompt to be formatted correctly like song lyrics - with each lyric on a newline. Since this model has been trained on formatted lyrics, the prompt needs to look the same to produce above average results.
input() doesn't work, because hitting return submits the text. I've also tried sys.stdin.read() as well and nothing seems to happen, just returns ' '.
Is it because I'm running it in a notebook? I'm only like 8 months deep into this python hobby, so I could be asking for something that can't happen.
Here's the code, would appreciate any ideas you've got.
prompt = input('Input Prompt:')
gpt2.generate(sess,
length=200,
temperature=.99,
prefix= prompt, #this is where the prompt goes
nsamples=5,
top_p=.9,
batch_size=5,
run_name='run1'
)
To take multiple lines of input and put them in a list of strings, you can use sys.stdin.readlines() which will keep accepting returns until you give it an EOF [ctrl + d in *nix, ctrl + z in Windows].
E.g.:
user_input = sys.stdin.readlines("Favourite foods followed by EOF:") # User gives input...
print(user_input)
Output:
>> ["Spam\n", "Spam\n", "Spam\n"]
Obviously this leaves you with newlines, so you could do something hacky like:
user_input = [line.rstrip() for line in sys.stdin.readlines()]
Which will give you:
>> ["Spam", "Spam", "Spam"]
Sounds like an interesting ML problem, though dealing with a list of strings may complicate things significantly. You might want to make them one long string using something like join, e.g.
" ".join(user_input) # Used with a separator of " ", but you could use newlines or something
Which gives one string of:
>> "Spam Spam Spam"
Can't you use a while loop to read the input? e.g.
prompt = []
line = input("Input prompt ending with an empty line: ")
while line:
prompt.append(line)
line = input()
prompt = "\n".join(prompt)