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().
python - How do I read from stdin? - Stack Overflow
Preferred method of reading from stdin?
Standard idiom for reading from stdin, writing to stdout?
linux - How to pass stdin to python script - Unix & Linux Stack Exchange
Videos
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.
Hi, just wondering if using input() or sys.stdin is the preferred method for reading from stdin in python. What are the differences and what is more readable/pythonesque?
# Using input()
while True:
try:
line = input()
...
except EOFError:
break
# Using sys.stdin
for line in sys.stdin:
line = line.strip()
...alias test='echo $(python test.py $1)'
$1 is not defined in an alias, aliases aren't shell functions; they're just text replacement; so your test hello gets expanded to echo $(python test.py ) hello, which gets expanded to echo ['test.py'] hello.
If you want a shell function, write one! (and don't call your function or alias test, that name is already reserved for the logical evaluation thing in your shell).
function foo() { echo $(python test.py $1) }
foo hello
But one really has to wonder: Why not simply make test.py executable (e.g. chmod 755 test.py) and include the #!/usr/bin/env python3 first line in it? Then you can just run it directly:
./test.py hello darkness my old friend
Your question is confusingly worded, but I seems you just want to execute an alias passing a parameter to your script.
I think this is what you want.
alias runtest='python test.py'
As otherwise mentioned, shell functions can be preferable to aliases -- allowing for less trivial arg handling.
So in this example:
function runtest() { python test.py "$1" ; }