Convert your for-loop into a so-called list comprehension (you don't need eval
/ exec
and wrap the whole thing in a string as the current top answer suggests):
In [1]: [i for i in range(3)]
Out[1]: [0, 1, 2]
You can also keep your print()
statement if you want it on multiple lines, but the return value (None
) will be put in the array that is returned, so you'll get this:
In [2]: [print(i) for i in range(3)]
0
1
2
Out[2]: [None, None, None]
To suppress that final output line, you can add a semicolon:
In [3]: [print(i) for i in range(3)];
0
1
2
So much for ipython3
, but perhaps more usefully, what about command-line usage? You can't do python3 -c 'import sys; for line in sys.stdin: print(line)'
but you can use list comprehension:
$ python3 -c '[print(i) for i in range(3)]'
0
1
2
So if you want to run a bit of python over each line:
$ cat inputfile
two
examples
$ cat inputfile | python3 -c 'import sys; [print(line.strip().upper()) for line in sys.stdin]'
TWO
EXAMPLES
(You can replace cat infile |
with <infile
but this seemed more accessible for those not familiar with Bash syntax, and those who are familiar can trivially replace it.)