iamsudip myshellv2 20130718-162640


Posted:

The assignment was

  1. To write a command greet, which will say Hi! to user. Solution: Imported getpass module. It did the rest
  2. To write a command stock [NASDAQ], which will show the current share price of given NASDAQ symbol. Solution: Imported sharevalue module, which was our previous assignment. So just used it. I am too lazy to write same code again. Well we have to use the requests liabrary. So modified the code of sharevalue. Modified code is also given here.

Code

 1 from cmd2 import Cmd
 2 from getpass import getuser
 3 from sharevalue import share
 4 
 5 __version__ = '0.1'
 6 
 7 class Application(Cmd):
 8     """
 9     The main Application class
10 
11     """
12 
13     def __init__(self):
14         Cmd.__init__(self)
15 
16     def do_hello(self, line):
17         print "Hello:", line
18 
19     def do_sayit(self, line):
20         print "Python Rocks!"
21 
22     def do_greet(self, line):
23         print "Hi! %s" %(getuser())
24 
25     def do_stock(self, line):
26         share(line)
27 
28 if __name__ == '__main__':
29     app = Application()
30     app.cmdloop()

Code for sharevalue using requests liabrary

 1 #!/usr/bin/env python
 2 
 3 import requests
 4 import sys
 5 
 6 def share(nasdaq):
 7 
 8     """
 9     Here all work is being done.
10 
11     :arg nasdaq: NASDAQ symbol
12     """
13 
14     #Making the link in 'link' string to fetch data
15     link = 'http://download.finance.yahoo.com/d/quotes.csv?s='+nasdaq+'&f=l1'
16     print 'Fetching recent share value of '+nasdaq
17 
18     share_value = requests.get(link)
19 
20     print '\n'+'Current share price of company '+nasdaq+': '+share_value.text
21     share_value.close()
22 
23 
24 if __name__ == '__main__':
25 
26     #Counting the NASDAQ Symbol (Arguments)
27     count = len(sys.argv) - 1
28 
29     #Checking if atleast one symbol available or not
30     if count >= 1:
31 
32         #NASDAQ symbol available passing it to main() function
33         i=0
34         while i < count:
35             i+=1
36             share(sys.argv[i])

How to execute code

Run the above script like:

$ python psh.py

Example output

Here example output is given below:

(Cmd) (virt0)sudip@sudip-mint virtual $  python psh.py
(Cmd) stock GOOG
Fetching recent share value of GOOG

Current share price of company GOOG: 915.60

(Cmd) (virt0)sudip@sudip-mint virtual $  python psh.py
(Cmd) greet
Hi! sudip
Contents © 2013 dgplug - Powered by Nikola
Share
UA-42392315-1