Learning streams and redirection with Python scripts
Standard I/O Streams
By default, the input is provided by the keyboard at the text terminal and the output and error are shown on the screen. This is the case not only for our Python scripts, but for all system commands.
Redirection of Standard Output
This process is provided to us by the operating system and can be really useful when you want to store the output of a command in a file, instead of just looking at it on a screen. To redirect the standard output of a program to a file we use the greater than or >
symbol. (or the arrow pointing to the right)
user@ubuntu:~$ cat stdout_example.py
#/usr/bin/env python3
print("Hello World!")
user@ubuntu:~$ ./stdout_example.py
Hello World!
user@ubuntu:~$ ./stdout_example.py > new_file.txt
user@ubuntu:~$ cat new_file.txt
Hello World!
There's also a way to append files to the destination using >>
symbol.
user@ubuntu:~$ cat stdout_example.py
#/usr/bin/env python3
print("Hello World!")
user@ubuntu:~$ ./stdout_example.py
Hello World!
user@ubuntu:~$ ./stdout_example.py > new_file.txt
user@ubuntu:~$ cat new_file.txt
Hello World!
user@ubuntu:~$ ./stdout_example.py >> new_file.txt
user@ubuntu:~$ cat new_file.txt
Hello World!
Hello World!
Redirection of Standard Input
Instead of using the keyboard to send data into a program, we can use the less than or <
symbol to read the contents of a file.
user@ubuntu:~$ cat new_hello.txt
Hello there,
user@ubuntu:~$ cat streams_hello.py
#/usr/bin/env python3
data = input()
print(data + "John!")
user@ubuntu:~$ ./streams_hello.py < new_hello.txt
Hello there, John!
This is expected because the input was read from a file. It reads the input from the "new_hello.txt" file and appends "John!" to it, printing the result "Hello there, John!".
The output can also be redirected using >
symbol.
user@ubuntu:~$ cat new_hello.txt
Hello there,
user@ubuntu:~$ cat streams_hello.py
#/usr/bin/env python3
data = input()
print(data + "John!")
user@ubuntu:~$ ./streams_hello.py < new_hello.txt > hello_output.txt
user@ubuntu:~$ cat hello_output.txt
Hello there, John!
The "streams_hello.py" script reads the input from "new_hello.txt" using standard input (stdin) and prints the output to standard output (stdout). The command redirects the input from "new_hello.txt" and captures the output in the "hello_output.txt" file.