The post Python Code Examples appeared first on PythonForBeginners.com.
]]>pywhois is a Python module for retrieving WHOIS information of domains. pywhois works with Python 2.4+ and no external dependencies [Source]
In this script I’m using 8 possible answers, but please feel free to add more as you wish. There are 20 answers inside the Magic 8 Ball, and you can find them all here.
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
Additional Resources
Find all mp3 files with os.walk and fnmatch
In an earlier post “OS.walk in Python“, I described how to use os.walk and showed some examples on how to use it in scripts. In this article, I will show how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.
This post will show how you can make a small and easy-to-use port scanner program written in Python.
Backup all MySQL databases, with timestamp.
Backup all MySQL databases, one in each file with a timestamp on the end using ConfigParser.
To make a request to the Web search API, we have to import the modules that we
need.
Pxssh is based on pexpect. It’s class extends pexpect.spawn to specialize setting up SSH connections.
This script can be used to parse date and time.
Bitly allows users to shorten, share, and track links (URLs). It’s a way to save, share and discover links on the web.
The smtplib module defines an SMTP client session object that can be used to send
mail to any Internet machine with an SMTP or ESMTP listener daemon. SMTP stands for Simple Mail Transfer Protocol.
Finding all files in the path that ends with a certain extension
This short script uses the os.listdir function (that belongs to the OS module) to search through a given path (“.”) for all files that endswith “.txt”.
Command Line speedtest.net via tespeed
Speedtest.net is a connection analysis website where users can test their internet
speed against hundreds of geographically dispersed servers around the world.
Search computer for specific files
In this article, I will show how to use the os.walk() module function to walk a
directory tree, and the fnmatch module for matching file names.
Knowing how to parse JSON objects is useful when you want to access an API
from various web services that gives the response in JSON.
Get the Geo Location of an IP Address
Time for a script again, this one will geolocate an IP address based on input from the user. For this script, we will be using a bunch of Python modules to accomplish this.
Get the username from a prompts
This script will ask the user for its username, by using the raw_input function. Then a list of allowed users is created named user1 and user2. The control statement checks if the input from the user matches the ones that are in the allowed users list.
This script will use the Twitter API to search for tweets.
In this post, I will show you how you can do it without that by just using
datetime.datetime.now() .
The second part of the post is about the the timedelta class, in which we can see
the difference between two date, time, or datetime instances to microsecond
resolution.
Python Game : Rolling the dice
This is a classic “roll the dice” program.
Monitor Apache / Nginx Log File
This small script will count the number of hits in a Apache/Nginx log file.
This script will show all entries in the file that is specified in the log file
variable.
Count how many days until a birthday
In this post, I will show you how you can print out the dates and times by just using datetime.datetime.now().
This small program extends the previous guessing game I wrote about in this
: post “Guessing Game”.
Guessing Game written in Python
This script is an interactive guessing game, which will ask the user to guess a
number between 1 and 99.
You can use Pythons string and random modules to generate passwords.
OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up.
This script converts speed from KM/H to MPH, which may be handy for calculating
speed limits when driving abroad, especially for UK and US drivers.
Get all the links from a website
In this script, we are going to use the re module to get all links from any website.
Celsius and Fahrenheit Converter
This script converts temperature between Fahrenheit to Celsius.
Additional Resources
How to use the Vimeo API in Python
In this post we will be looking on how to use the Vimeo API in Python.
Show the most popular videos on YouTube
This program will show how we can use the API to retrieve feeds from YouTube.
This script will calculate the average of three values.
Check your external IP address
This is a simple Python script to check which external IP address you have.
This is a Python script of the classic game “Hangman”.
Python Command Line IMDB Scraper
This script will ask for a movie title and a year and then query IMDB for it.
Here we link to other sites that provides Python code examples.
ActiveState Code – Popular Python recipes
Nullege – Search engine for Python source code
The post Python Code Examples appeared first on PythonForBeginners.com.
]]>The post DNS Lookup With Python appeared first on PythonForBeginners.com.
]]>
import socket
addr1 = socket.gethostbyname('google.com')
addr2 = socket.gethostbyname('yahoo.com')
print(addr1, addr2)
Which will output the following ip addresses:
173.194.121.9 98.138.253.109
The post DNS Lookup With Python appeared first on PythonForBeginners.com.
]]>The post How to Use MySQL Connector/Python appeared first on PythonForBeginners.com.
]]>To install MySQL Connector/Python simply use pip to install the package.
pip install mysql-connect-python --allow-external mysql-connector-python
Recommended Course
Connecting to database and committing to it is very simple.
import mysql.connector
connection = mysql.connector.connect(user="username",
password="password",
host="127.0.0.1",
database="database_name")
cur = connection.cursor()
cur.execute("INSERT INTO people (name, age) VALUES ('Bob', 25);")
connection.commit()
cur.close()
connection.close()
The post How to Use MySQL Connector/Python appeared first on PythonForBeginners.com.
]]>The post Getting popular pages from your Apache logs appeared first on PythonForBeginners.com.
]]>In this example, we only want to know the URLs from GET requests. We will use the wonderful Counter which is in Python’s Collections
import collections
logfile = open("yourlogfile.log", "r")
clean_log=[]
for line in logfile:
try:
# copy the URLS to an empty list.
# We get the part between GET and HTTP
clean_log.append(line[line.index("GET")+4:line.index("HTTP")])
except:
pass
counter = collections.Counter(clean_log)
# get the Top 50 most popular URLs
for count in counter.most_common(50):
print(str(count[1]) + " " + str(count[0]))
logfile.close()
The post Getting popular pages from your Apache logs appeared first on PythonForBeginners.com.
]]>The post How to use Envoy appeared first on PythonForBeginners.com.
]]>Recently I stumble upon Envoy. Envoy is a wrapper around the subprocess module and
is supposed to humanize subprocess of Python.
Its written by Kenneth Reitz (the author of “Requests: HTTP for Humans“)
It was written to be an easy to use alternative to subprocess.
“Envoy: Python Subprocesses for Humans.”
Envoy is available from PyPI and can be installed with pip.
Search for the Envoy package via the pip command-line tool.
pip search envoy
” envoy – Simple API for running external processes. “Install Envoy
$ pip install envoy
Just like with any other Python modules, we have to import them first.
Start your Python interpreter and type “import envoy”
import envoy
Great, Envoy is imported, now we can start to discover its functions etc.
After you have imported a module in Python, it’s always good to see what functions
,classes and methods that the module provides. One way of doing that is using
“dir(envoy)”.
That will list the names of all functions and variables, that are defined in the
Envoy module.
>>> dir(envoy)
That will give you an output like this:
['Command', 'ConnectedCommand', 'Response', '__builtins__', '__doc__', '__file__',
'__name__', '__package__', '__path__', '__version__', 'connect', 'core', 'expand_args',
'os', 'run', 'shlex', 'subprocess', 'threading’]
If you want to get one name per line, just run a simple for loop:
>>> for i in dir(envoy): print i
This output shows you one name per line:
...
Command
ConnectedCommand
Response
__builtins__
__doc__
__file__
__name__
__package__
__path__
__version__
connect
core
expand_args
os
run
shlex
subprocess
threading
>>>
You can also use “help(envoy)” to get the documentation on all the functions.
Let’s take a look at the “run” method for Envoy.
To check the uptime of our machine, we can use the “uptime” command.
r = envoy.run("uptime”)
To see the output, we add “std_out”:
>>> r.std_out
'15:11 up 6 days, 1:04, 3 users, load averages: 0.55 0.57 0.61
‘
To get the status code, add “status_code” to your object.
print r.status_code
0
Run a command, get the response:
>>> print r
To get the standard error, add “std_err”.
r.std_err
Get history.
r.history
[<response 'uptime'="">]
Check for the Chrome process
r = envoy.run("ps aux |grep Chrome")
print r.std_out
In our last example, I make use of multiple commands.
import envoy
cmd = ['date', "uptime", "w"]
r = envoy.run(cmd)
print r.std_out
Get the status code of all commands
import envoy
cmd = ['date', "uptime", "w"]
for command in cmd:
r = envoy.run(cmd)
print r.status_code
Get the status code + the output of each command
import envoy
cmd = ['date', "uptime", "w"]
for command in cmd:
r = envoy.run(cmd)
print r.status_code, r.std_out
Envoy has become my main library to handle external command calls.
It was written to be an easy to use alternative to subprocess and the convenience
of envoy.run is really great.
https://github.com/kennethreitz/envoy
http://stackoverflow.com/search?q=envoy
The post How to use Envoy appeared first on PythonForBeginners.com.
]]>The post How to use FTP in Python appeared first on PythonForBeginners.com.
]]>This article will show how you can use FTP in Python with the help of the
ftplib module.
The ftplib module in Python allows you to write Python programs that perform a
variety of automated FTP jobs. You can easily connect to a FTP server to retrieve
files and process them locally.
To use the ftplib module in Python, you first have to import it into your script.
To “open” a connection to the FTP Server, you have to create the object.
Once the connection is made (opened), you can use the methods in the ftplib
module.
Several methods are available in two flavors: one for handling text files and
another for binary files.
You can easily navigate the directory structure, manage and download files.
This program will first connect to a FTP server (ftp.cwi.nl) and then list the
files and directories in the FTP server root directory using the LIST() method.
from ftplib import FTP
ftp = FTP('ftp.cwi.nl') # connect to host, default port
ftp.login() # user anonymous, passwd anonymous@
ftp.retrlines('LIST') # list directory contents
Our second program opens a connection to ‘ftp.sunet.se’ as the user ‘anonymous’
with an email address of ‘[email protected]’
It then lists the files and directories on the FTP server by using the dir()
method.
The output is saved to the ‘files’ variable.
I then use print to see the files on screen.
If I want I to change directory I would just use ftp.cwd(path) to do so.
To close the FTP connection, use the quit() method.
import ftplib
ftp = ftplib.FTP('ftp.sunet.se', 'anonymous', '[email protected]')
print "File List: "
files = ftp.dir()
print files
ftp.cwd("/pub/unix") #changing to /pub/unix
Connect to the given host and port.
The default port number is 21, as specified by the FTP protocol specification.
It is rarely needed to specify a different port number.
This function should be called only once for each instance
It should not be called at all if a host was given when the instance was created.
All other methods can only be used after a connection
has been made.
The optional timeout parameter specifies a timeout in seconds for the connection
attempt.
If no timeout is passed, the global default timeout setting will be used.
Return the welcome message sent by the server in reply to the initial connection.
This message sometimes contains disclaimers or help information that may be
relevant to the user
Log in as the given user.
The passwd and acct parameters are optional and default to the empty string.
If no user is specified, it defaults to ‘anonymous’.
If user is ‘anonymous’, the default passwd is ‘anonymous@’.
This function should be called only once for each instance, after a connection
has been established.
It should not be called at all if a host and user were given when the instance
was created.
Most FTP commands are only allowed after the client has logged in.
The acct parameter supplies “accounting information”; few systems implement this.
Retrieve a file in binary transfer mode.
Command should be an appropriate RETR command: ‘RETR filename’.
The callback function is called for each block of data received, with a single
string argument giving the data block.
The optional maxblocksize argument specifies the maximum chunk size to read on
the low-level socket object created to do the actual transfer.
A reasonable default is chosen. rest means the same thing as in the transfercmd()
method.
Retrieve a file or directory listing in ASCII transfer mode.
Command should be an appropriate RETR command or a command such as LIST, NLST or
MLSD.
LIST retrieves a list of files and information about those files.
NLST retrieves a list of file names.
On some servers, MLSD retrieves a machine readable list of files and information
about those files.
The callback function is called for each line with a string argument containing
the line with the trailing CRLF stripped.
The default callback prints the line to sys.stdout.
Produce a directory listing as returned by the LIST command, printing it to
standard output.
The optional argument is a directory to list (default is the current server
directory).
Multiple arguments can be used to pass non-standard options to the LIST command.
If the last argument is a function, it is used as a callback function as for
retrlines(); the default prints to sys.stdout.
This method returns None.
Remove the file named filename from the server.
If successful, returns the text of the response, otherwise raises error_perm on
permission errors or error_reply on other errors.
Set the current directory on the server.
Create a new directory on the server.
Return the pathname of the current directory on the server.
Send a QUIT command to the server and close the connection.
This is the “polite” way to close a connection, but it may raise an exception if
the server responds with an error to the QUIT command.
This implies a call to the close() method which renders the FTP instance useless
for subsequent calls.
Close the connection unilaterally.
This should not be applied to an already closed connection such as after a
successful call to quit().
After this call the FTP instance should not be used any more.
After a call to close() or quit() you cannot reopen the connection by issuing
another login() method).
For more information, please see the official Python Documentation
The post How to use FTP in Python appeared first on PythonForBeginners.com.
]]>The post Sending emails using Google appeared first on PythonForBeginners.com.
]]>A common task for system administrators and developers is to use scripts to send emails if an error occurs.
Using Googles SMTP servers are free to use and works perfectly fine to relay emails. Note that Google has a sending limit: “Google will temporarily disable your account if you send messages to more than 500 recipients or if you send a large number of undeliverable messages. ” As long as you are fine with that, you are good to go.
Sending mail is done with Python’s smtplib using an SMTP (Simple Mail Transfer Protocol) server. Since we will use Google’s SMTP server to deliver our emails, we will need to gather information such as server, port, authentication. That information is easy to find with a Google search.
Outgoing Mail (SMTP) Server – requires TLS or SSL: smtp.gmail.com
Use Authentication: Yes
Port for TLS/STARTTLS: 587
Port for SSL: 465
Server timeouts: Greater than 1 minute, we recommend 5
Account Name or User Name: your full email address (including @gmail.com or @your_domain.com)
Email Address: your email address ([email protected] or username@your_domain.com) Password: your Gmail password
Begin with opening up your favorite text editor and import the smtplib module at the top of your script.
import smtplib
Already at the top we will create some SMTP headers.
fromaddr = '[email protected]'
toaddrs = '[email protected]'
msg = 'Enter you message here’
Once that is done, create a SMTP object which is going to be used for connection with the server.
server = smtplib.SMTP("smtp.gmail.com:587”)
Next, we will use the starttls() function which is required by Gmail.
server.starttls()
Next, log in to the server:
server.login(username,password)
Then, we will send the email:
server.sendmail(fromaddr, toaddrs, msg)
You can see the full program below, by now you should be able to understand what it does.
import smtplib
# Specifying the from and to addresses
fromaddr = '[email protected]'
toaddrs = '[email protected]'
# Writing the message (this message will appear in the email)
msg = 'Enter you message here'
# Gmail Login
username = 'username'
password = 'password'
# Sending the mail
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
The post Sending emails using Google appeared first on PythonForBeginners.com.
]]>The post Tweet Search with Python appeared first on PythonForBeginners.com.
]]>Twitter’s API is REST-based and will return results as either XML or JSON, as well as both RSS and ATOM feed formats. Public timelines can be accessed by any client, but all other Twitter methods require authentication.
The program is well documented and should be straightforward. Open up a text editor, copy & paste the code below.
Save the file as: “tweet_search.py” and exit the editor.
Let’s take a look at the program below that we call tweet_search.py
#!/usr/bin/python
import json
import sys
import urllib2
import os
usage = """
Usage: ./tweet_search.py 'keyword'
e.g ./tweet_search.py pythonforbeginners
Use "+" to replace whitespace"
e.g ./tweet_search.py "python+for+beginners"
"""
# Check that the user puts in an argument, else print the usage variable, then quit.
if len(sys.argv)!=2:
print (usage)
sys.exit(0)
# The screen name in Twitter, is the screen name of the user for whom to return results for.
# Set the screen name to the second argument
screen = sys.argv[1]
# Open the twitter search URL the result will be shown in json format
url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)
#convert the data and load it into json
data = json.load(url)
#to print out how many tweets there are
print len(data), "tweets"
# Start parse the tweets from the result
# Get only text
for tweet in data["results"]:
print tweet["text"]
# Get the status and print out the contents
for status in data['results']:
print "(%s) %s" % (status["created_at"], status["text"])
Let’s break down the script to see what it does.
The script starts with importing the modules we are going to need
Line 3-6
import json
import sys
import urllib2
import os
We create a usage variable to explain how to use the script.
Line 8-14
usage = """
Usage: ./tweet_search.py 'keyword'
e.g ./tweet_search.py pythonforbeginners
Use "+" to replace whitespace"
e.g ./tweet_search.py "python+for+beginners"
"""
On Line 16 we check that the user puts in an argument, else print the usage variable, then quit.
if len(sys.argv)!=2:
print (usage)
sys.exit(0)
Line 21-24 sets the Twitter screen name to the second argument.
screen = sys.argv[1]
Line 27 open the twitter search URL and the result will be shown in json format.
url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)
Line 30 converts the data and loads it into json
data = json.load(url)
On Line 33 we print out the number of tweets
print len(data), "tweets"
From Line 38 we start to parse the tweets from the result
for tweet in data["results"]:
print tweet["text"]
The last thing we do in this script is to get the status and print out the contents (Line 42)
for status in data['results']:
print "(%s) %s" % (status["created_at"], status["text"])
Go through the script line by line to see what it does. Make sure to look at it, and try to understand it.
The post Tweet Search with Python appeared first on PythonForBeginners.com.
]]>The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.
]]>A magic 8-ball is a hollow sphere made out of plastic and printed to look like the 8-ball from a billiards game. It is filled with a dark blue or black liquid, usually alcohol, and contains a 20-sided die. Instead of numbers on the die, the sides are printed with a variety of yes, no, and maybe-type answers. A standard Magic 8 Ball has twenty possible answers, including ten affirmative answers, five non-committal answers, and five negative answers.
To play the magic 8-ball game, the player holds the ball and thinks of a yes or no question. They then shake the ball, which agitates a printed die floating in the dark blue liquid inside of the ball. When the shaking stops, the die settles to the bottom of the ball, revealing a yes, no, or vague answer. You can read more about this game on its wiki page.
The core functionality of the magic 8-ball game is to predict the outcome of a certain event from 20 possible outcomes in a random manner. To implement this functionality, we can use the random module in Python.
We can implement the magic 8-ball game in Python using the randint() function with if-else statements. Alternatively, we can also use the choice() function defined in the random module in Python to implement the magic 8-ball game. Let us discuss both approaches one by one.
To implement the magic 8-ball game in Python using the randint() function, we will use the following steps.
input() function.randint() function. For this, we will pass the value 1 as its first input argument and the value 20 as its second input argument. You can observe the above process in the following example.
import random
while True:
question=input("Ask the magic 8 ball a question: (press enter to quit) ")
answer=random.randint(1,20)
if question=="":
print("Stopping the Game.")
break
if answer==1:
print("It is certain.")
elif answer==2:
print("It is decidedly so.")
elif answer==3:
print("Without a doubt.")
elif answer==4:
print("Yes definitely.")
elif answer==5:
print("You may rely on it.")
elif answer==6:
print("As I see it, yes.")
elif answer==7:
print("Most likely.")
elif answer==8:
print("Outlook good.")
elif answer==9:
print("Yes.")
elif answer==10:
print("Signs point to yes.")
elif answer==11:
print("Reply hazy, try again.")
elif answer==12:
print("Ask again later.")
elif answer==13:
print("Better not tell you now.")
elif answer==14:
print("Cannot predict now.")
elif answer==15:
print("Concentrate and ask again.")
elif answer==16:
print("Don't count on it.")
elif answer==17:
print("My reply is no.")
elif answer==18:
print("My sources say no.")
elif answer==19:
print("Outlook not so good.")
elif answer==20:
print("Very doubtful.")
Output:
Ask the magic 8 ball a question: (press enter to quit) Python is awesome
Yes.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit)
Stopping the Game.
In the above code, we have used 20 if-else blocks to implement the answers. You can observe that the if-else blocks made the code redundantly large. Hence, we can use a Python dictionary to imitate the functionality of the if-else blocks. For this, we will use the numbers as the keys and the answers for each number as the corresponding values.
After predicting a number using the randint() method, we can get the answer from the dictionary and print it as shown below.
import random
answer_dict={1:"It is certain.",
2:"It is decidedly so.",
3: "Without a doubt.",
4:"Yes definitely.",
5:"You may rely on it.",
6:"As I see it, yes.",
7:"Most likely.",
8:"Outlook good.",
9:"Yes.",
10:"Signs point to yes.",
11:"Reply hazy, try again.",
12:"Ask again later.",
13:"Better not tell you now.",
14:"Cannot predict now.",
15:"Concentrate and ask again.",
16:"Don't count on it.",
17:"My reply is no.",
18:"My sources say no.",
19:"Outlook not so good.",
20:"Very doubtful."}
while True:
question=input("Ask the magic 8 ball a question: (press enter to quit) ")
answer=random.randint(1,20)
if question=="":
print("Stopping the Game.")
break
answer_string=answer_dict[answer]
print(answer_string)
Output:
Ask the magic 8 ball a question: (press enter to quit) Python is awesome.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit) PFB is great.
Reply hazy, try again.
Stopping the Game.
In this example, we first generate a random number between 1 to 20 using the randint() function to predict the answer. As we have already defined the dictionary with numbers as keys and the possible answers as their values, we use the indexing operator to get the string value associated with the random number and print it.
Instead of the randint() function, we can also use the choice() function defined in the random module to implement the magic 8-ball game. The choice() function takes a list as its input argument and returns a random element from the list. To implement the game, we will put all 20 answers in a list. After this, whenever the user asks a question, we will select a value from the list using the choice function and print it as shown in the following example.
import random
answer_list=['It is certain.',
'It is decidedly so.',
'Without a doubt.',
'Yes definitely.',
'You may rely on it.',
'As I see it, yes.',
'Most likely.',
'Outlook good.',
'Yes.',
'Signs point to yes.',
'Reply hazy, try again.',
'Ask again later.',
'Better not tell you now.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't count on it.",
'My reply is no.',
'My sources say no.',
'Outlook not so good.',
'Very doubtful.']
while True:
question=input("Ask the magic 8 ball a question: (press enter to quit) ")
if question=="":
print("Stopping the Game.")
break
answer_string=random.choice(answer_list)
print(answer_string)
Output:
Ask the magic 8 ball a question: (press enter to quit) Python is awesome
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is great
You may rely on it.
Ask the magic 8 ball a question: (press enter to quit) PFB is awesome.
My reply is no.
Ask the magic 8 ball a question: (press enter to quit) PFB is good.
Yes definitely.
Ask the magic 8 ball a question: (press enter to quit)
Stopping the Game.
In this example, we have stored all the possible answers in a list. When the user asks for an answer, we directly select a random answer from the list using the choice() function and print it.
In this article, we discussed three ways to implement the magic 8-ball game in Python. To learn more about Python programming, you can read this article on rolling the dice game in Python. You might also like this article on python trees.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
The post Magic 8-ball Game Written in Python appeared first on PythonForBeginners.com.
]]>The post CommandLineFu with Python appeared first on PythonForBeginners.com.
]]>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
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:
Format is one of the following:
I prefer using the json format and that is also what I’m using in the program below.
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?
...
...
The post CommandLineFu with Python appeared first on PythonForBeginners.com.
]]>