So I wrote a cool little python script for terminal commands that I get sick of entering. Most of the script is explained in docstrings and comments. Looking for useful terminal commands or things I missed or could have done better.

I'm actually quite proud of it. :)

#!/usr/bin/env python 

'''Local refers to the host computer[127.0.0.1], 
System refers to the system, [run] runs the command in a host network 
enviroment.'''
__default__ = "/" 
__pythondefault__ = "/Users/self/Desktop/Python3" 
__vers__ = 1.0 
__auth__ = "SirPrinceKai"
import os 
from fabric.api import *

def Erase():
    print "Removes the bits and pieces from your trash can."
    local("rm -rf ~/.Trash") #erases local trash can bin# 

def EchoPath():
    if __pythondefault__:
        lspyfol = os.chdir(__pythondefault__) 
        print lspyfol 
        local("echo $PATH ") 
    else:
        local("echo $PATH") #full_path,alter for windows compatibility# 

class InternetSettings(object):
    '''Class that deals with all Internet Settings.'''

    def WifiUpDownHandler(*args):
        print "Use ifconfig/ipconfig for more information about your system."
        iface = raw_input("Enter iface: ") #lo0;gif0;stf0;en0;en1;p2p0;fw0;vnic0;vnic1;utun0#
        up_down = str(raw_input("Enter command: ")) #up;down# 
        print "Don't forget to put the interface back up for inet transmissions."
        local("sudo ifconfig " + iface + " " + up_down)

    def PingHostSite(*args):
        print "Use this to see if you have an active inet connection."
        host_site = str(raw_input("Enter a host site to ping: "))
        local("ping -o " + host_site)

    def TracerouteSite(*args):
        print "Use this to trace the route to the host site. Also useful for finding IP Adresses."
        tracer = str(raw_input("Enter a site to traceroute: "))
        local("traceroute " + tracer)

    def HTTPServerCheck(*args):
        print "Hyper Text Transfer Protocol Checking."
        http_server = str(raw_input("Enter a site to check (HTTP Server Check: 4"))
        local("curl -I " + http_server + "| head -n 1")

    def DomainInfo(*args):
        print "Use for discovering domain information. Use a valid IP Address."
        domain_info = str(raw_input("Enter discover domain information: "))
        local("dig " + domain_info + "A")

    def RoutingTable(*args):
        print "Complete routing table information. Awesome."
        show_routing_table = str(raw_input("Show INET routing table? "))
        if show_routing_table.lower() == "yes" or show_routing_table.lower() == "y":
            local("netstat -r")
        show_active = str(raw_input("Show active connections? "))
        if show_active.lower() == "yes" or show_active.lower() == "y":
                local("netstat -an")
        show_net_stats = str(raw_input("Show network statistics? "))
        if show_net_stats.lower() == "yes" or show_net_stats.lower() == "y":
            local("netstat -s")

def TaskKill():
    local("top") 
    _processid = raw_input("Enter a process identification: ") 
    local("kill pid " + _processid)

def RestartOSX():
    print "WARNING: This will restart OSX. Suggesting you save your work."
    areYouSure = str(raw_input("Are you sure you want to reboot? "))
    if areYouSure.lower() == "yes" or areYouSure.lower() == "y":
        print "Your system will now reboot."
        local("sudo shutdown -r now")
    else:
        print "Restart Canceled." 
    return None

def ShutdownOSX():
    print "WARNING: This will shut down OSX. Suggesting you save your work."
    areYouSure = str(raw_input("Are you sure you want to shut down? "))
    if areYouSure.lower() == "yes" or areYouSure.lower() == "y":
        print "Your system will now shut down."
        local("sudo shutdown now")
    else:
        print "Shutdown Canceled."
    return None 

def PutToSleepAfter15Min():
    print "This will put your display to sleep after 15 minutes."
    print "You can adjust this time by editing this file. (Default is 15 min)."
    areYouSure = str(raw_input("Are you sure you want to set your display sleep mode? "))
    if areYouSure.lower() == "yes" or areYouSure.lower() == "y":
        print "Your display is set for sleep in 15 minutes."
        # Change to pmset 30 for 30 minute increment
        local("sudo pmset displaysleep 15")
    else:
        print "Display Change Canceled."
    return None

def ShowHiddenFiles():
    print "This configuration will either show or hide your hidden files."
    print "CAUTION: I'd only use this if you know what you are doing..."
    fdresponse = str(raw_input("Show hidden files? "))
    if fdresponse.lower() == "yes" or fdresponse.lower() == "y":
        local("defaults write com.apple.finder AppleShowAllFiles TRUE")
    elif fdresponse.lower() == "no" or fdresponse.lower() == "n":
        local("defaults write com.apple.finder AppleShowAllFiles FALSE")
    else:
        return None 

def ListAllOpenFiles():
    print "This is a really long list. If you would like to cancel, press control + z"
    local("lsof")

def EjectCD():
    print "It will not always be disk1. Refer to your manual for disk information."
    mount_disk = str(raw_input("What is the name of the disk you want to eject? "))
    local("diskutil eject " + mount_disk)

class TextManipulation(object):
    '''Commands that deal with text manipulation (clipboard or file).
    For commands that use pbcopy, you can use file as an input instead.
    Just swap pbpaste for: cat [/path/to/filename]. To put the results
    into a file on your desktop, just swap | pbcopy for:  > ~/Desktop/filename.txt
    '''
    def CountLinesInClipboard(*args):
        local("pbpaste | wc -l")

    def CountWordsInClipboard(*args):
        local("pbpaste | wc -w")

    def SortTextLinesThenCopy(*args):
        local("pbpaste | sort | pbcopy") 

    def ReverseTextThenCopy(*args):
        local("pbpaste | rev | pbcopy")

    def StripDuplTextThenCopyOne(*args):
        # output is sorted 
        local("pbpaste | sort | uniq | pbcopy")

    def FindDuplStripDublTextThenCopyOne(*args):
        # output is sorted
        local("pbpaste | sort | uniq -d | pbcopy")

    def StripDuplThenCopyOne(*args):
        # complete duplicate stripping 
        local("pbpaste | sort | uniq -u | pbcopy") 

    def TidyHTMLThenCopy(*args):
        local("pbpaste | tidy | pbcopy")

    def DisplayFirstFiveLines(*args):
        local("pbpaste | head -n 5")

    def DisplayLastFiveLines(*args):
        local("pbpaste | tail -n 5") 

    def ConvertTabsToSpaces(*args):
        local("pbpaste | expand | pbcopy")


def DisplayHistory():
    print "If unable to display history, return to main bash shell and enter 'history'"
    local("history")

def ConvertFileToHTML():
    print "You must pass the full pathname to the file as an argument."
    print "Creates a duplicate HTML file (i.e, Web Page) at file location."
    ftc = raw_input("Enter a file to conver to HTML (Supported formats are .txt, .rtf, .doc): ")
    if ftc:
        local("textutil -convert html " + ftc)

def Nano():
    print "You must pass a full file name location as an argument."
    print "Edits a file with the Nano editor. (Works AWESOME!)"
    # use full file location with fte arg 
    fte = raw_input("Enter a file to edit with Nano: ")
    if fte:
        local("nano " + fte)

def Clear():
    print "Now you see me..."
    local("clear") 
    print "Now you don't!"

def ChangeItunesDefault():
    print "This changes your default pointing iTunes links to your local library."
    print "If you need further help, you probably should not be using this."
    lnkrespond = raw_input("Point iTunes links to local library? ") 
    if lnkrespond.lower() == "yes" or lnkrespond.lower() == "y":
        local("defaults write com.apple.iTunes invertStoreLinks -bool YES")
    elif lnkrespond.lower() == "no" or lnkrespond.lower() == "n":
        local("defaults write com.apple.iTunes invertStoreLinks -bool NO")



if __name__ == "__main__":
    print "\nTerminal Command Handler " + str(__vers__)
    print "By: " + str(__auth__)
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print "Available tasks are: (To exit, press control + z)"
    print "1. Erase"
    print "2. Echo Path"
    print "3. Internet Settings"
    print "4. Task Kill"
    print "5. Restart OSX"
    print "6. Shutdown OSX"
    print "7. Put To Sleep After 15 Min"
    print "8. Show Hidden Files"
    print "9. List All Open Files"
    print "10. Eject CD"
    print "11. Text Manipulation"
    print "12. Display History"
    print "13. Convert File To HTML"
    print "14. Nano"
    print "15. Clear"
    print "16. Change Itunes Default"
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"

    def Master():
        catch_command = int(raw_input(">>> "))
        if catch_command == 1:
            Erase()
            Master() 
        if catch_command == 2:
            EchoPath() 
            Master()
        if catch_command == 3: 
            inetset = InternetSettings()
            print "\nAvailable internet settings are:"
            print "1. Wifi Up/Down Handler"
            print "2. Ping Host Site"
            print "3. Traceroute Site"
            print "4. HTTP Server Check"
            print "5. Domain Information"
            print "6. Routing Table"
            protocol = int(raw_input(">>> "))
            if protocol == 1:
                inetset.WifiUpDownHandler()
            if protocol == 2:
                inetset.PingHostSite()
            if protocol == 3:
                inetset.TracerouteSite()
            if protocol == 4:
                inetset.HTTPServerCheck()
            if protocol == 5:
                inetset.DomainInfo()
            if protocol == 6:
                inetset.RoutingTable()
            Master()
        if catch_command == 4:
            TaskKill() 
            Master()
        if catch_command == 5:
            RestartOSX() 
            Master()
        if catch_command == 6:
            ShutdownOSX() 
            Master()
        if catch_command == 7:
            PutToSleepAfter15Min()
            Master()
        if catch_command == 8:
            ShowHiddenFiles() 
            Master()
        if catch_command == 9:
            ListAllOpenFiles()
            Master()
        if catch_command == 10:
            EjectCD()
            Master()
        if catch_command == 11: 
            manipulate = TextManipulation()
            print "\nAvailable text commands are:"
            print "1. Count Lines In Clipboard"
            print "2. Count Words In Clipboard"
            print "3. Sort Text Lines Then Copy"
            print "4. Reverse Text Then Copy"
            print "5. Strip Duplicate Double Text Then Copy"
            print "6. Find Duplicate, Strip Double Text Then Copy"
            print "7. Strip Duplicate Then Copy"
            print "8. Tidy HTML Then Copy"
            print "9. Display First 5 Lines"
            print "10. Display Last 5 Lines"
            print "11. Convert Tabs To Spaces"
            sst = int(raw_input(">>> "))
            if sst == 1:
                manipulate.CountLinesInClipboard() 
            if sst == 2:
                manipulate.CountWordsInClipboard()
            if sst == 3:
                manipulate.SortTextLinesThenCopy()
            if sst == 4:
                manipulate.ReverseTextThenCopy()
            if sst == 5:
                manipulate.StripDuplTextThenCopyOne()
            if sst == 6:
                manipulate.FindDuplStripDublTextThenCopyOne()
            if sst == 7:
                manipulate.StripDuplThenCopyOne()
            if sst == 8:
                manipulate.TidyHTMLThenCopy()
            if sst == 9:
                manipulate.DisplayFirstFiveLines()
            if sst == 19:
                manipulate.DisplayLastFiveLines()
            if sst == 11:
                manipulate.ConvertTabsToSpaces()
            Master()
        if catch_command == 12:
            DisplayHistory()
            Master()
        if catch_command == 13:
            ConvertFileToHTML()
            Master()
        if catch_command == 14:
            Nano()
            Master()
        if catch_command == 15:
            Clear() 
            Master()
        if catch_command == 16:
            ChangeItunesDefault()
            Master()
    Master() 
Gribouillis commented: good idea +13

Recommended Answers

All 4 Replies

You have infinite recursion to Master, function names should be small_case_with_underscores.

I used recursive with master to return the main function, otherwise it would just exit, and I didn't want that. As far as the lowercase, I knew that I was just being hardheaded and fancied the uppercase for this script. Probably best I go back and change them before something breaks later. >.<

Thanks Tony! :)

Given the menu-based structure of your program, you may find some reusable ideas in this snippet that I wrote a long time ago to help menu based scripts writers!

Awesome, Thankyou Gribouillis!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.