Chapter Ten · Outside the Program

Talking to the World

A useful program remembers things between runs, fetches information it does not have, keeps its settings and secrets out of its code, and takes instructions on the command line. This chapter covers all four, including one real request to a live web service, and what to do when that service does not answer.

So far your programs have lived inside your computer: they read files you made and printed results to your terminal. This chapter opens the doors. A program can save its data and find it again tomorrow. It can ask a service on the internet for something it cannot know by itself, such as today's exchange rate. And it can become a proper tool, run with instructions on the command line instead of answering questions every time.

Five topics. JSON, the text format that gives a program a memory. One request to a real web service, using the requests package installed in Chapter 9. What to do when the network fails, which it will. Settings and secrets, and why they never belong in your code. And command-line arguments, which turn a script into a tool with --help built in.

This is the one chapter that depends on a service outside this book. The service, its address and the exact shape of its answers are confined to Topics 2 and 3, and they are the parts most likely to change after this was written.

Your script and the world around it
One run of a script that talks to the world
On your computerexpenses.pyrates.jsonsettings and secrets
Across the networka request goes outJSON comes backor nothing comes back
A web servicean exchange-rate API
When the service is silent, the script uses what it saved last time and says how old it is.

Topics in This Chapter