puspita23 Myshellv1 20130718-164810    Posted:


Problem

Write a script to define 2 commands 'stock' and 'greet' for the shell cmd2 imported from Cmd module. 1.Stock <nasdaqsymb> will return the current sharevalue of the symbol entered. 2.Greet, will return "Hi!, <username>"

Solution

From 'Greet' command I have used getuser() From 'Stock <nasdaqsymb> I have used requests.get()

Code

::
from cmd2 import Cmd from getpass import getuser import sys import requests

__version__ = '0.1'

class Application(Cmd):

""" The main Application class """

def __init__(self):
Cmd.__init__(self)
def do_hello(self, line):
print "Hello:", line
def do_sayit(self,line):
print "Python Rocks!"
def do_stock(self,line):
""" using requests.get() to get the url and then printing the value of the stock inputted """ r=requests.get('http://download.finance.yahoo.com/d/quote.csv?s='+line+'&f=l1') data=r.text value=float(data) print value
def do_greet(self,line):
""" getuser() used to get the user that is logged in """ print "Hi! %s" %(getuser())
if __name__ == '__main__':
app = Application() app.cmdloop()

Link to the code is https://github.com/puspita23/puspita_utility/blob/master/myshell/psh.py

Comments

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

Comments

JCaselles myshellv1 20130718-162028    Posted:


My Shell v1

Assignment: Wrote a script that will use cmd2 module to emulate a command shell. We need to define 2 functions for this shell: greet, which shall return "Hi, <user>" and stock <NASDAQSYMB>, which shall return the current share value of the given company.

Solution:

For the user greeting function, i've used getpass.getuser(). For the share value, requests module has been used, along with yahoo finance service: download.finance.yahoo.com

Code:

Link to the Code

 1 #!/usr/bin/env python
 2 
 3 import requests
 4 from cmd2 import Cmd
 5 from sys import exit
 6 from getpass import getuser
 7 
 8 
 9 class Application(Cmd):
10     """
11     Main Application class
12 
13     """
14 
15     def __init__(self):
16         Cmd.__init__(self)
17 
18 
19     def do_greet(self, line):
20         """
21         Prints a greeting for the current user.
22 
23         """
24 
25         print "Hi, %s" % getuser()
26 
27 
28     def do_stock(self, line):
29         """
30         This method prints the share value of the company whose nasdaq symbol
31         is given. It is argument safe: no matter how many arguments you pass
32         to the command, it will only use the first one.
33 
34         returns the share value if the symbol is correct.
35         Otherwise, returns error.
36 
37         """
38 
39 
40         content = requests.get("http://download.finance.yahoo.com"
41                                 "/d/quotes.csv?s=%s&f=l1" % line.split(" ")[0])
42 
43         if content.text.find("0.00") == -1:
44             print content.text.rstrip()
45 
46         else:
47             print "Error. Make sure the symbol is a valid NASDAQ symbol"
48 
49 
50 
51 if __name__ == "__main__":
52     app = Application()
53     app.cmdloop()

Comments

ThyArmageddon MyShellv1 20130718-155029    Posted:


MyShellv1

Even though the name of the project is MyShellv1, the actual version of it is 0.3. Anyway, this script will use sharevalue.py written previously, which was edited to be used as module as well, which uses, by itself, YahooAPI.py.

Code

YahooAPI.py

"""
Yahoo API Module
================

YahooFinance Class
------------------
This class will save the ticker in a correct link format
and will output the correct value when value is called

"""

import requests


class YFinance(object):

    """
    The YahooAPI has a correct link
    and the value returned from Yahoo Finance
    """

    def __init__(self):
        """
        The default link is None
        """
        self._link = None

    @property
    def link(self):
        """
        This will return the link when needed
        to access the website and get the value
        """
        return self._link

    @property
    def value(self):
        """
        We try to connect to the link
        if everything goes well, we get the value
        we check if the value is not 0 and return it
        if we can't connect we will return -1
        """
        try:
            fobj = requests.get(self._link)
            data = fobj.text
            value = float(data)
            fobj.close()
            if value == 0.0:
                return
            return value

        except IOError:
            return -1

    @link.setter
    def link(self, ticker):
        """
        The link recieves a ticker and saves it as a link
        The link will be used later to get the information
        from the web page.
        """
        link = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=l1" \
            % ticker
        self._link = link

sharevalue.py

#!/usr/bin/env python
"""
This python script will use the API modules
availables to check the value of a specific
ticker online and return it
"""

import sys
from YahooAPI import YFinance

def Stock(ticker=''):
    if not ticker:
        print "No Ticker"
        sys.exit(1)

    else:
        """
        We create a class from the Yahoo API
        We set the ticker argv[1]
        We ask for the value of the market
        """
        finance = YFinance()
        finance.link = ticker
        value = finance.value

        """
        We test if value is set first
        if it is not we exit because the ticker is wrong
        We, then, test if value is set to -1
        if it is we exit because we couldn't connect
        """
        if not value:
            print """
            You submitted a ticker that doesn't exist
            Please try a different ticker than %s
            """ % ticker
            sys.exit(1)
        if value == -1:
            print """
            We were able to connect to the website
            The website might be down
            Please check your connection and try again.
            """
            sys.exit(1)

        else:
            return value


if __name__ == '__main__':
    """
    We start by testing the number of arguments
    and exit if the number of arguments is less
    than 2
    """

    if len(sys.argv) != 2:
        print """
        Incorrect argument length

        Usage:
        sharevalue.py <ticker>
        """
        sys.exit(1)

    """
    We create a class from the Yahoo API
    We set the ticker argv[1]
    We ask for the value of the market
    """
    finance = YFinance()
    finance.link = sys.argv[1]
    value = finance.value

    """
    We test if value is set first
    if it is not we exit because the ticker is wrong
    We, then, test if value is set to -1
    if it is we exit because we couldn't connect
    """
    if not value:
        print """
        You submitted a ticker that doesn't exist
        Please try a different ticker than %s
        """ % (sys.argv[1])
        sys.exit(1)
    if value == -1:
        print """
        We were able to connect to the website
        The website might be down
        Please check your connection and try again.
        """
        sys.exit(1)

    """
    If everything goes well, we print the value
    """
    print """
        The current value of %s is %.2f
    """ % (sys.argv[1], value)

myshellv1

#!/usr/bin/env python
from cmd2 import Cmd
from getpass import getuser
from sharevalue import Stock

__version__ = '0.3'


class Application(Cmd):
    """
    The main Application class

   """

    def __init__(self):
        Cmd.__init__(self)

    def do_hello(self, line):
        print "Hello:", line

    def do_sayit(self, line):
        print "Python Rocks!"

    def do_greet(self, line):
        """
        Greet the user by printing
        the username.
        """
        print "Hello %s" % getuser()

    def do_stock(self, line):
        """
        Call Stock from sharevalue to get the stock market
        value of a ticker.
        """
        print Stock(line)


if __name__ == '__main__':
    app = Application()
    app.cmdloop()

Comments

iamsudip myshellv1 20130718-153857    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.

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()

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

Comments

ThyArmageddon MyShellv1 20130718-153507    Posted:


MyShellv1

Even though the name of the project is MyShellv1, the actual version of it is 0.3. Anyway, this script will use sharevalue.py written previously, which was edited to be used as module as well, which uses, by itself, YahooAPI.py.

Code

YahooAPI.py

"""
Yahoo API Module
================

YahooFinance Class
------------------
This class will save the ticker in a correct link format
and will output the correct value when value is called

"""

import urllib2


class YFinance(object):

    """
    The YahooAPI has a correct link
    and the value returned from Yahoo Finance
    """

    def __init__(self):
        """
        The default link is None
        """
        self._link = None

    @property
    def link(self):
        """
        This will return the link when needed
        to access the website and get the value
        """
        return self._link

    @property
    def value(self):
        """
        We try to connect to the link
        if everything goes well, we get the value
        we check if the value is not 0 and return it
        if we can't connect we will return -1
        """
        try:
            fobj = urllib2.urlopen(self._link)
            data = fobj.read()
            value = float(data)
            fobj.close()
            if value == 0.0:
                return
            return value

        except IOError:
            return -1

    @link.setter
    def link(self, ticker):
        """
        The link recieves a ticker and saves it as a link
        The link will be used later to get the information
        from the web page.
        """
        link = "http://download.finance.yahoo.com/d/quotes.csv?s=%s&f=l1" \
            % ticker
        self._link = link

sharevalue.py

#!/usr/bin/env python
"""
This python script will use the API modules
availables to check the value of a specific
ticker online and return it
"""

import sys
from YahooAPI import YFinance

def Stock(ticker=''):
    if not ticker:
        print "No Ticker"
        sys.exit(1)

    else:
        """
        We create a class from the Yahoo API
        We set the ticker argv[1]
        We ask for the value of the market
        """
        finance = YFinance()
        finance.link = ticker
        value = finance.value

        """
        We test if value is set first
        if it is not we exit because the ticker is wrong
        We, then, test if value is set to -1
        if it is we exit because we couldn't connect
        """
        if not value:
            print """
            You submitted a ticker that doesn't exist
            Please try a different ticker than %s
            """ % ticker
            sys.exit(1)
        if value == -1:
            print """
            We were able to connect to the website
            The website might be down
            Please check your connection and try again.
            """
            sys.exit(1)

        else:
            return value


if __name__ == '__main__':
    """
    We start by testing the number of arguments
    and exit if the number of arguments is less
    than 2
    """

    if len(sys.argv) != 2:
        print """
        Incorrect argument length

        Usage:
        sharevalue.py <ticker>
        """
        sys.exit(1)

    """
    We create a class from the Yahoo API
    We set the ticker argv[1]
    We ask for the value of the market
    """
    finance = YFinance()
    finance.link = sys.argv[1]
    value = finance.value

    """
    We test if value is set first
    if it is not we exit because the ticker is wrong
    We, then, test if value is set to -1
    if it is we exit because we couldn't connect
    """
    if not value:
        print """
        You submitted a ticker that doesn't exist
        Please try a different ticker than %s
        """ % (sys.argv[1])
        sys.exit(1)
    if value == -1:
        print """
        We were able to connect to the website
        The website might be down
        Please check your connection and try again.
        """
        sys.exit(1)

    """
    If everything goes well, we print the value
    """
    print """
        The current value of %s is %.2f
    """ % (sys.argv[1], value)

myshellv1

#!/usr/bin/env python
from cmd2 import Cmd
from getpass import getuser
from sharevalue import Stock

__version__ = '0.3'


class Application(Cmd):
    """
    The main Application class

   """

    def __init__(self):
        Cmd.__init__(self)

    def do_hello(self, line):
        print "Hello:", line

    def do_sayit(self, line):
        print "Python Rocks!"

    def do_greet(self, line):
        """
        Greet the user by printing
        the username.
        """
        print "Hello %s" % getuser()

    def do_stock(self, line):
        """
        Call Stock from sharevalue to get the stock market
        value of a ticker.
        """
        print Stock(line)


if __name__ == '__main__':
    app = Application()
    app.cmdloop()

Comments

ThyArmageddon User Finder 20130718-134348    Posted:


User Finder Assignment

This User Finder script will output the users on the current system. When the user uses useradd to create a new user, useradd will use /etc/login.defs to assign automatic UIDs from the UID range specified in that configuration file. So the assumption is that the users will generally not bother setting their own UID and let useradd handle it and their UID will be in the range.

Code

#!/usr/bin/env python
"""
This script will output the users on the current system
"""

from sys import exit
from os import path
from pwd import getpwall
import re


def print_users():
    """
    We get the information from passwd and the range of UIDs.
    Then we print all the users in the range.
    """
    passwd_info = getpwall()

    min_uid, max_uid = find_uid_range()

    print "Users on this system are:"
    print "-------------------------"

    for user in passwd_info:
        if (not user.pw_uid) or (user.pw_uid >= min_uid and user.pw_uid <= max_uid):
            print user.pw_name


def find_uid_range():
    """
    When a user uses useradd the system will assign a UID in the range
    mentioned in login.defs. So the assumption is that very rarely users
    choose their own UIDs and let the system choose instead. So we
    parse the login.defs file and get the values of UID_MIN and
    UID_MAX and return it as this is the range of UIDs autoassigned
    to users.
    """
    if path.exists("/etc/login.defs"):
        f = open("/etc/login.defs").read()
        min_uid_pattern = re.compile('\n\s*UID_MIN\s+(\d+)\s*\n')
        max_uid_pattern = re.compile('\n\s*UID_MAX\s+(\d+)\s*\n')
        min_uid = re.findall(min_uid_pattern, f)
        max_uid = re.findall(max_uid_pattern, f)
        return int(min_uid[0]), int(max_uid[0])
    else:
        print "Could not find login.defs file on system"
        exit(1)


if __name__ == '__main__':

    print_users()
    exit(0)

Comments

rahulc93 planetfeedparser 20130718-055654    Posted:


In this assignment, we will be reading the RSS feeds of this site , parse the feed, and print the title of the blog posts and their respective authors.

Source Code

The code for the above problem can be found here

Solution

The solution to the problem is shown below.

#!/usr/bin/env python

import feedparser

feed = feedparser.parse("http://planet.fedoraproject.org/rss20.xml")  # parsing the feed from the recquired URL
for x in range(len(feed.entries)):  # iterating throgh the items in the entries list
    author, title = feed.entries[x].title.split(":", 1)  # extracting the names of authors and titles from the list
        print "\nAuthor: ", author, "\nTitle: ", title  # printing the information obtained

Run the program

To run this script, save the file as planetfeedparser.py, and follow the steps.

  1. Change the file's permissions and make it executable:

    $ chmod +x planetfeedparser.py
    
  2. Execute the file:

    $ ./planetfeedparser.py
    

Alternatively, you can try:

$ python planetfeedparser.py

Comments

Christina-B planetparser 20130717-181744    Posted:


Problem- Generate a program in python which will display the title and author of blog

Description

  1. Open the url http://planet.fedoraproject.org using urllib2

  2. Read the contents of the site in a systematic manner using BeautifulSoup module.

  3. Read the title and name of author and print it.

    Click the link below to see the program

    link

    Execute the program using following command

    $ chmod +x planetparser.py

    $ python planetparser.py

Comments

JCaselles user finder v3 - spwd module 20130717-173930    Posted:


Assignment

Write a code that will print the list of available user to log in.

Solution

Use of spwd module, that returns a list of the databases of all users whith proper shell init configuration (i.e. they don't haver either /bin/false or /sbin/nologin). From this list, there still are few that are not able to be used for login, and are marked with "*" or "!" in the password index of the database (ps_pwd, or 1). When we discard those with this symbols in the password field, we end up with only those users capable of login.

Link to Code at GitHub

#!/usr/bin/env python

from spwd import getspall
from sys import exit

def get_users_list ():

    """
    This function prints the list of users that are able to login
    into the system. To achieve this, we use the spwd module and its function
    getspall(), which returns a list of each user password database,
    like /etc/shadow file. Then we filter it to print just the users
    that have a proper password, and not marked with "*" or "!", which means
    they are not suited for login into the system.

    """


    user_list = getspall()

    filtered_list =  [user.sp_nam for user in user_list \
                      if user.sp_pwd.find("*") == -1 \
                      and user.sp_pwd.find("!") == -1]

    for x in filtered_list:
        print x


if __name__ == "__main__":
    get_users_list()
    exit(0)

Comments

Contents © 2013 dgplug - Powered by Nikola
Share
UA-42392315-1