Creating a boot-up menu

We will now apply the methods introduced in the previous scripts and reapply them to create a menu that we can customize to present a range of quick-to-run commands and programs.

How to do it…

Create the menu.py script using the following code:

#!/usr/bin/python3
#menu.py
from subprocess import call

filename="menu.ini"
DESC=0
KEY=1
CMD=2

print ("Start Menu:")
try:
  with open(filename) as f:
    menufile = f.readlines()
except IOError:
  print ("Unable to open %s" % (filename))
for item in menufile:
  line = item.split(',')
  print ("(%s):%s" % (line[KEY],line[DESC]))
#Get user input
running = True
while(running):
  user_input = input()
  #Check input, and execute command
  for item in menufile:
    line = item.split(',')
    if (user_input == line[KEY]):
      print ("Command: " + line[CMD])
      #call the script
      #e.g. call(["ls", "-l"])
      commands = line[CMD].rstrip().split()
      print (commands)
      running = False
      #Only run command is one if available
      if len(commands):
        call(commands)
  if (running==True):
    print ("Key not in menu.")
print ("All Done.")
#End

Create a menu.ini file that will contain the following menu items and commands:

Start Desktop,d,startx
Show IP Address,i,hostname -I
Show CPU speed,s,cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
Show Core Temperature,t,sudo /opt/vc/bin/vcgencmd measure_temp
Exit,x,

You can add your own commands to the list, creating your own custom start-up menu. The script will assume the menu.ini file is formatted correctly, so if you experience an error (for example ErrorIndex) it may be because the file is not as expected (such as missing commas or blank lines). We could use except ErrorIndex: to handle any errors, however we are better off highlighting there is a problem within the input file so that it can be fixed instead.

How it works…

In order to execute other programs from within a Python script, we need to use the call command. This time, we only wish to use the call part of the subprocess module, so we can simply use from subprocess import call. This just imports the part we need.

We will open the file and read all the lines into a menufile list. We can then process each item (or line of the file) using item.split(','), which will create a new list consisting of each section of the line divided by the ',' symbol, as follows:

line = ['Start Desktop', 'd', 'startx
']

As shown by the print statement, we can now access each section independently, so we can print the key we need to press for a specific command and the description of the command.

Once we have printed the entire menu of commands, we will wait for the user's input. This is done inside a while loop; it will continue to run until we set the condition inside running to False. This means that if an invalid key is pressed, we can enter another key until a command is selected or the exit item is used. We will then check the input key to see if it matches the allocated key for the menu item, as follows:

user_input == line[KEY]

If there is a match, we will extract the command we wish to call. The call command requires a command and its arguments to be a list, so we will use .split() to break up the command part into a list (where each space in the command is a new item in the list). Also note that there is /n after startx, this is the end of the line character from the menu.ini file. We will remove this first using .rstrip(), which removes any whitespace (spaces, tabs, or line endings) from the end of a string.

Once the command is formatted into a list of arguments, we will set running to False (so the while loop will not enter another loop), execute our command, and finish the script. If the user selects x, there will be no commands set, allowing us to exit the menu without calling anything. The script produces a small menu of options, as shown in the following:

Start Menu:
(d):Start Desktop
(i):Show IP Address
(s):Show CPU speed
(t):Show Core Temperature
(x):Exit
g
Key not in menu.
i
Command: hostname -I
['hostname', '-I']
All Done.

There's more…

To make the script run each time, we will start the Raspberry Pi; we can call it from .bash_profile, which is a bash script that runs when the user's profile is loaded.

Create or edit the file as follows:

nano -c ~/.bash_profile

Add the following commands (assuming menu.py is located in the /home/pi/python_scripts directory):

cd /home/pi/python_scripts
python3 menu.py

When done, save and exit (Ctrl + X, Y, and Enter).

The next time you power up your Raspberry Pi, you will have a menu to run your favorite commands from, without needing to remember them.

Note

You can also run Python scripts directly, without the python3 command, making them executable, as follows:

chmod +x menu.py

Now type ./menu.py and the script will run using the program defined within the file by the first line, as follows:

#!/usr/bin/python3
..................Content has been hidden....................

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