Saturday, July 4, 2009

Terminal command shortcut scirpt

You know those terminal commands that you execute all the time but are too lazy to put in a shell alias or those special commands you need a lot of time to figure out and then mostly forget about it and then the next time you need it you cruse yourself you did not save it somewhere? This script aims to address this problems.

It stores commands terminated with newline in a data file (~/.scdata). When you invoke it with the number argument, it executes that line number (beginning with 0). Without argument it list the available commands with id's and prompts for id to execute.

Now, when you figured out some complicated command with a lot of options, like 'rsync -av /myhome /backup_drive' you can simply echo it to the data file (echo 'rsync -av /myhome /backup_drive' >> ~/.scdata) and recall it anytime with the prompt utility.

Your ~/.scdata with 4 commands (0-3) could look like this:

echo hello
cp foo bar
rsync -av /myhome /backup_drive
echo 'and so forth'

Now running the script with argument '2' ($ sc.py 2) for instance would run the rsync command.

Syntax highlighted version here.

#! /usr/bin/env python3

"""
Terminal command shortcut scirpt.

This script reads a command data file (~/.scdata) and executes commands from it.

There are two command execution models:
1. by argement, if you invoke it with a number, it executes this command
and exits. If you invoke it with -e opion, it opens the command file
for editing and then enters the main loop.
2. by loop, if you invoke it withouth an argument, it prints the
availible commands and promts for command number (id) to execute.

There are also 2 special non-numeric loop commands:
e: edit command file and return to main loop
q: quit program
"""

import os, sys, time

def get_editor():
try:
editor = os.environ['EDITOR']
except:
editor = 'vim'
return editor

def read_data(editor, data_file):
try:
with open(data_file, 'r') as f:
data = f.readlines()
data = [item.strip() for item in data]
data = dict(enumerate(data))
return data
except:
print('Data file not found, first start?.. Creating data file')
print('Please add some command to it..')
time.sleep(3)
with open(data_file, 'w') as f:
pass
os.system(editor + ' ' + data_file)
return read_data()

if __name__ == '__main__':

editor = get_editor()
data_file = os.path.join(os.path.expanduser('~'), '.scdata')

data = read_data(editor, data_file)

if len(sys.argv) > 1:
if sys.argv[1] == '-e':
print('Opening data file for editing..')
time.sleep(1)
os.system(editor + ' ' + data_file)
try:
cmd_task = int(sys.argv[1])
os.system('clear')
print('executing ', data[cmd_task], '\n')
os.system(data[cmd_task])
print('\nexecution done, exiting..')
sys.exit()
except (IndexError, ValueError):
pass

while True:
os.system('clear')
print('Shell command shortcut utility\n' +
'==============================\n\n' +
'Currently availible commands are:\n')
for cmd_task, cmd in data.items():
print(cmd_task, '\t', cmd)
print('\nPlease enter a command (e, q, or number)\n')
try:
cmd_task = input('% ')
if cmd_task == 'e':
os.system(editor + ' ' + data_file)
data = read_data(editor, data_file)
continue
elif cmd_task == 'q':
print('Quit.. bye!')
sys.exit()
else:
cmd_task = int(cmd_task)
assert(cmd_task <= len(data))
except (AssertionError, ValueError, KeyError):
print('Please enter a valid input ' +
'(h, e, q or number)')
time.sleep(1)
else:
os.system('clear')
print('executing \'{1}\' ..\n'.format(data[cmd_task]))
time.sleep(1)
os.system(data[cmd_task])
print('\nexecution done, hit a key to return..')
input()

No comments:

Post a Comment