• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Code Snippets / CommandLineFu with Python

CommandLineFu with Python

Author: PFB Staff Writer
Last Updated: May 20, 2020

Overview

One of the best methods to practice Python coding is to study some code and try them out yourself. By doing a lot of code exercises, you will get a much better understanding of what it really does.

In other words, learning by doing. To help you improve your Python coding skill, I’ve created a program below which is using the API from CommandLineFu.com

CommandLineFu API

A common first step when you want to use a Web-based services is to see if they have an API.

Luckily for me, Commandlinefu.com provides one and can be found here:

“The content of commandlinefu.com is available in a variety of different formats for you to do what you like with. Any page which contains a list of commands (such as the listings by tag, function or user) can be returned in a format of your choice through a simple change to the request URL.”

The example URL that they provide is:

http://www.commandlinefu.com/commands/’command-set’/’format’/

where: command-set is the URL component which specifies which set of commands to return.

Possible values are:

  • browse/sort-by-votes
  • tagged/163/grep
  • matching/ssh/c3No

Format is one of the following:

  • plaintext
  • json
  • rss

I prefer using the json format and that is also what I’m using in the program below.

Creating the “Command Line Search Tool”

I think we have all the API information we need, so let’s get to it. The program is well documented and should be straightforward.

Open up a text editor, copy & paste the code below. Save the file as: “commandlinefu.py” and exit the editor.

#!/usr/bin/env python27
import urllib2
import base64
import json
import os
import sys
import re

os.system("clear")
print "-" * 80
print "Command Line Search Tool"
print "-" * 80

def Banner(text):
    print "=" * 70
    print text
    print "=" * 70
    sys.stdout.flush()

def sortByVotes():
    Banner('Sort By Votes')
    url = "http://www.commandlinefu.com/commands/browse/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    #print json.dumps(response,indent=2)
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesToday():
    Banner('Printing All commands the last day (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-day/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesWeek():
    Banner('Printing All commands the last week (Sort By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-week/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByVotesMonth():
    Banner('Printing: All commands from the last months (Sorted By Votes) ')
    url = "http://www.commandlinefu.com/commands/browse/last-month/sort-by-votes/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
        print c['command']

def sortByMatch():
    #import base64
    Banner("Sort By Match")
    match = raw_input("Please enter a search command: ")
    bestmatch = re.compile(r' ')
    search = bestmatch.sub('+', match)
    b64_encoded = base64.b64encode(search)
    url = "http://www.commandlinefu.com/commands/matching/" + search + "/" + b64_encoded + "/json"
    request = urllib2.Request(url)
    response = json.load(urllib2.urlopen(request))
    for c in response:
        print "-" * 60
  print c['command']

print """
1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command
 
Press enter to quit
"""

while True:
  answer = raw_input("What would you like to do? ")

 if answer == "":
    sys.exit()
  
  elif answer == "1":
   sortByVotes()
 
  elif answer == "2":
   print sortByVotesToday()
  
  elif answer == "3":
   print sortByVotesWeek()
 
  elif answer == "4":
   print sortByVotesMonth()
  
  elif answer == "5":
   print sortByMatch()
 
  else:
   print "Not a valid choice"

When you run the program, you will be presented with a menu in which you can make your choices.


--------------------------------------------------------------------------------
Command Line Search Tool
--------------------------------------------------------------------------------

1. Sort By Votes (All time)
2. Sort By Votes (Today)
3. Sort by Votes (Week)
4. Sort by Votes (Month)
5. Search for a command

Press enter to quit

What would you like to do?
...
...

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Code Snippets Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us