Executing Python scripts

Python is no different to other tools—you can execute Python scripts via the command line,
using a Python command):

$ echo 'print("Hello world!")' > script.py`
$ python script.py
Hello world!

In the preceding code, we first created a simple Python script and then ran it in the second line. Any Python script can be executed like that. In other words, you can write a program in Python and share it with others, or use it yourself via the command line, without going through the hassle of firing up Jupyter and executing cells one by one!

For learning purposes, let's modify the geocode.py file we wrote in Chapter 6, First Script – Geocoding with Web APIs, into a full-blown script that geocodes addresses one by one, or in batches.

First, let's copy it into a new folder (here, we assume we are in the chapter's folder):

cp ../Chapter06/geocode.py .

Now, the script has all functions, but there is no code that will be executed upon running:
python Chapter09/geocode.py will return nothing. Let's add some code:

echo 'print(nominatim_geocode("13 Rue de la Chapelle, 70250 Ronchamp, France"))' >> geocode.py

Of course, you can also add the same code via the VS Code editor.

Now, let's run the script:

$ python Chapter09/geocode.py
[{'place_id': 84388496, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright', 'osm_type': 'way', 'osm_id': 34915920, 'boundingbox': ['47.7043284', '47.7045899', '6.6202675', '6.6207617'], 'lat': '47.7044779', 'lon': '6.62051522099271', 'display_name': 'Chapelle Notre-Damedu-Haut, 13, Rue de la Chapelle, Ronchamp, Lure, Haute-Saône, Bourgogne-Franche-Comté, France métropolitaine, 70250, France', 'class': 'amenity', 'type': 'place_of_worship', 'importance': 1.14130071139371, 'icon': 'https://nominatim.openstreetmap.org/images/mapicons/place_of_worship_unknown3.p.20.png'}]

Perfect! However, we need to solve two issues in order for this script to be useful:

  • First, the preceding code now runs every time you import from geocode.py.
  • Second, we need to create some sort of interface to feed information—address or file paths—to our script.

First off, let's solve the first issue. Of course, we could separate the files we want to call from others, but that makes things too complex. Instead, there is a special pattern for this:

if __name__ == '__main__':
print(nominatim_geocode('13 Rue de la Chapelle, 70250 Ronchamp, France'))

In the preceding clause, __name__ is a special variable in the file's local namespace (Jupyter Notebooks don't have it). It is equal to __main__ if the file was called directly, and to other values if we import from it. Now, our geocoding will run from the command line, but not when we import from this file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset