Python for Perl programmers is a set of short posts showing how some of the most common Perl idioms can easily be implemented in Python. This time I'll show you how to translate code chunks using Perl's diamond operator to elegant Python code.
while (<>) {
...
}This loop written in Perl will iterate over all of the lines from standard input, whether it is pipe from another program or the list of the files specified as the program's arguments (argv). The same functionality can be done in Python by using the fileinput module, so the previous code snippet becomes:import fileinput for line in fileinput.input(): ...The default order of processing is:
sys.argv[1:]sys.stdin
If file name is specified as "-", the standard input is used instead. You can get more information on fileinput module in official Python documentation.
0 comments:
Post a Comment