Skip to content

Input/Output#

We looked at input and output in the Bash section. We discussed STDOUT and STDIN. We also looked at JSON output too (and even had an example in Python.)

Let's repeat the same thing here, but in Python.

Standard Input#

Much like in the case of Bash, a Python script can receive input via STDIN. Here's the original script from the Bash section:

1
2
3
4
5
import json
import sys

data = json.load(sys.stdin)
print(data['message'])

We can see that we used sys.stdin (from the sys module that was import-ed for us.) This provides us with access to the data inside of the STDIN "input" for our script. Let's execute it:

1
2
> echo '{"message": "Hello, world! My name is Mike"}' | python input_output_stdin.py
Hello, world! My name is Mike

The | is a pipe and even on Windows 10 in a PowerShell prompt (which is how I'm executing the code) it serves as a way of piping the output of one command into the input (the standard input) of another command.

Standard Output#

And standard output, or STDOUT, is simple enough to understand too:

1
print("Hello,. world!")

That's right! The print() function just writes to STDOUT by default. That can be changed with the file= parameter, but I'll leave that for you, dear reader, as an experiment.

Let's try this:

1
print('{"message": "Hello, world! My name is Mike"}')

And then execute is like this:

1
2
> python .\input_output_stdout.py | python .\input_output_stdin.py
Hello, world! My name is Mike

Easy.

JSON Output#

And finally, we can use Python to output JSON for us. As was discussed previously, JSON is used heavily in CloudOps and DevOps as APIs talk to each other and transfer data as JSON documents.

Python has extremely powerful JSON functionality, as we saw in our script earlier:

1
2
3
4
5
import json
import sys

data = json.load(sys.stdin)
print(data['message'])

Let's extend this a little bit, so that it prints JSON as well as reads it:

1
2
3
4
5
6
7
import json
import sys

data = json.load(sys.stdin)
print(data['message'])

print(json.dump({"message": "Hello, world! My name is Mike"}))

And then we execute our script:

1
2
3
> echo '{"message": "Hello, world! My name is Mike"}' | python input_output_json.py
Hello, world! My name is Mike
{"message": "Hello, world! My name is Mike"}

We can see the original JSON being read in (via standard input), and processed as we daw earlier. We're not also writing out (to standard output) a JSON document using the json.dumps() function.

Very clean and simple.