Python programs can read from unix pipelines. Here is a simple example how to read from stdin:
import sys
for line in sys.stdin: print(line)
Be aware that sys.stdin is a stream. It means that the for-loop will only terminate when the stream has ended.
You can now pipe the output of another program into your python program as follows:
$ cat myfile | python myprogram.py
In this example cat myfile can be any unix command that outputs to stdout.
Alternatively, using the fileinput module can come in handy:
import fileinput for line in fileinput.input(): process(line)
Using input() and raw_input()
Python 2.x Version ≥ 2.3
raw_input will wait for the user to enter text and then return the result as a string.
foo = raw_input("Put a message here that asks the user for input")
In the above example foo will store whatever input the user provides.
Python 3.x Version ≥ 3.0
return float(raw_input(msg))
except ValueError:
if err_msg is not None:
print(err_msg)
def input_number(msg, err_msg=None):
while True:
try:
return float(input(msg))
except ValueError:
if err_msg is not None:
print(err_msg)
And to use it:
user_number = input_number("input a number:
", "that's not a number!")
Or, if you do not want an "error message":
user_number = input_number("input a number: ")
input will wait for the user to enter text and then return the result as a string.
foo = input("Put a message here that asks the user for input")
In the above example foo will store whatever input the user provides.
Section 29.5: Function to prompt user for a number
def input_number(msg, err_msg=None):
while True:
try: