sys.stdin.readlines() returns a list of lines. If what you want is one long (multi-line) string, use sys.stdin.read().
python - How to use a string as stdin - Stack Overflow
How do I get sys.stdin.readline to read string
python - How do I read from stdin? - Stack Overflow
python - Write function result to stdin - Stack Overflow
Temporarily replace sys.stdin with a StringIO or cStringIO with the desired string.
>>> s = StringIO.StringIO('Hello, world!')
>>> sys.stdin = s ; r = raw_input('What you say?\n') ; sys.stdin = sys.__stdin__
What you say?
>>> r
'Hello, world!'
In Python >= 3.4, you can make it a bit more elegant by creating a _RedirectStream context manager.
import contextlib
import io
class redirect_stdin(contextlib._RedirectStream):
"""Context manager for temporarily receiving stdin from another source."""
_stream = "stdin"
def test():
a = input("Type something: ")
return a
if __name__=='__main__':
with redirect_stdin(io.StringIO("Hello World")):
returnValue = test()
This can be combined with the existing redirect_stdout and redirect_stderr decorators for even more flexibility. Somehow, stdin was not given the same treatment. You can read the diucussion on Python Issue #15805 for more context.
my prof is making us use sys.stdout and sys.stdin instead of input and print, and I'm having trouble with my code. I'm new so yea
sys.stdout.write ("Enter yes or no: ")
User7=str(sys.stdin.readline())
if User7 == yes:
sys.stdout.write ("Stock code:22138\n")
It keeps saying yes not defined so I'm a bit puzzled on how to do that..
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.
You could mock stdin with a file-like object?
Copyimport sys
import StringIO
oldstdin = sys.stdin
sys.stdin = StringIO.StringIO('asdlkj')
print raw_input('.') # .asdlkj
I was googling how to do this myself and figured it out. For my situation I was taking some sample input from hackerrank.com and putting it in a file, then wanted to be able to use said file as my stdin, so that I could write a solution that could be easily copy/pasted into their IDE. I made my 2 python files executable, added the shebang. The first one reads my file and writes to stdout.
Copy#!/Users/ryandines/.local/share/virtualenvs/PythonPractice-U9gvG0nO/bin/python
# my_input.py
import sys
def read_input():
lines = [line.rstrip('\n') for line in open('/Users/ryandines/Projects/PythonPractice/swfdump')]
for my_line in lines:
sys.stdout.write(my_line)
sys.stdout.write("\n")
read_input()
The second file is the code I'm writing to solve a programming challenge. This was mine:
Copy#!/Users/ryandines/.local/share/virtualenvs/PythonPractice-U9gvG0nO/bin/python
def zip_stuff():
n, x = map(int, input().split(' '))
sheet = []
for _ in range(x):
sheet.append( map(float, input().split(' ')) )
for i in zip(*sheet):
print( sum(i)/len(i) )
zip_stuff()
Then I use the operating system's pipe command to provide the buffering of STDIN. Works exactly like hackerrank.com, so I can easily cut/paste the sample input and also my corresponding code without changing anything. Call it like this: ./my_input.py | ./zip_stuff.py
Use split to split a string into a list, for example:
>>> '2 2 4 5 7'.split()
['2', '2', '4', '5', '7']
As you see, elements are string. If you want to have elements as integers, use int and a list comprehension:
>>> [int(elem) for elem in '2 2 4 5 7'.split()]
[2, 2, 4, 5, 7]
So, in your case, you would do something like:
import sys
list_of_lists = []
for line in sys.stdin:
new_list = [int(elem) for elem in line.split()]
list_of_lists.append(new_list)
You will end up having a list of lists:
>>> list_of_lists
[[3], [2], [2, 2, 4, 5, 7]]
If you want to have those lists as variables, simply do:
list1 = list_of_lists[0] # first list of this list of lists
list1 = list_of_lists[1] # second list of this list of lists
list1 = list_of_lists[2] # an so on ...
Here's one way:
import ast
line = '1 2 3 4 5'
list(ast.literal_eval(','.join(line.split())))
=> [1, 2, 3, 4, 5]
The idea is, that for each line you read you can turn it into a list using literal_eval(). Another, shorter option would be to use list comprehensions:
[int(x) for x in line.split()]
=> [1, 2, 3, 4, 5]
The above assumes that the numbers are integers, replace int() with float() in case that the numbers have decimals.