4 - Python Scripting
BASH and other scripting languages are fantastic in the shell and for quick or OS-specific scripts. But what if you want something a little more powerful and cross-platform?
What are we learning?
In this lesson we will:
Learn how to apply 'permanent' settings to BASH and Nano with run commands (.bashrc and .nanorc)
Confirm we have Python installed
Discuss an argument vector (argv)
Compare BASH to Python with the treats script
Run Commands
When you give arguments to a program that modify how the program works, these are sometimes called run commands. Some programs can store these options in a configuration file.
.bashrc
Let's edit the .bashrc file: nano .bashrc
Look for the lines containing "PS1" - use your ability to read code to discern what those mean / do
Feel free to customize yours to your liking (there's lots of details online)
.nanorc
Nano can also take run commands to modify how it works.
Try: man nano
Let's change tabs to spaces and a couple other things...
Make a new file in your home folder:
cd ~
nano .nanorcA couple personal preferences:
set tabstospaces
set tabsize 4
set linenumbers
set mouseSave and exit... restart nano to take a look
Python
BASH is powerful but it's more of an operating system scripting language - for talking to the kernel, making and reading files, etc... What if we want to write a program that is cross-platform and portable-ish?
Python is the Swiss army knife of scripting languages. It's not amazing at one thing - it's pretty good at all things. It's also a popular platform for learning, data analysis, and sharing libraries of code that do cool things.
Let's check if Python is installed:
python
Don't worry - it's actually there... python3
type exit() to get out of the interpreter
Let's create a system-wide alias for python3: sudo install python-is-python3
Python Treats
Let's recreate the Dog Treats program we wrote in BASH:
Create the script treats.py and add a shebang line at the top (where is the python executable?)
Make your script executable in Linux
We want to run the program like this: ./treats.py 3 2 1 (or similar)
How do we get command-line arguments in Python?
Can we successfully use Python to recreate the treats program?
Zero That Out
In the EXTRAS section of the first class task was the description of a boss who would give numbers to sum but if the boss made a mistake they would say the number zero meaning to not use the last number. Can we recreate the program in Python? Would this be easier than in BASH?
Reference: Python Tutorial (w3)