Skip to content

Python scripts

Files: * files/script.py

Executing python scripts

Show the script.py file and discuss options: * shebang * comment * import on the top * if __name__ == "__main__"

Execute the script:

python script.py

[
    {
        "vendor": "cisco",
        "os": "nxos",
        "ipaddr": "10.1.1.1"
    },
    {
        "vendor": "cisco",
        "os": "ios",
        "ipaddr": "10.2.1.1"
    },
    {
        "vendor": "arista",
        "os": "eos",
        "ipaddr": "10.1.1.2"
    }
]

Go to python interpreter and import the script.py file. Print the devices variable with json.

python

import script

print(script.devices)

import json
print(json.dumps(script.devices, indent=4))

Add the print statement to the script to print the content of the __name__ variable:

print(__name__)

Run the script again to show the content of the __name__ variable:

python script.py

Go to python interpreter and import the script.py file again. You can see that script is printed on the screen.

import script

Exit interpreter and run the script again with the -i option. Show them that you can print variables from here.

python -i script.py

print(device)