4 Replies - 527 Views - Last Post: 13 September 2014 - 04:04 PM Rate Topic: -----

#1 rmac362  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 10-September 14

*sys.argv - how does this work?

Posted 13 September 2014 - 03:43 PM

I was working on the anagram_db.py exercise from "Think Python" by Allen Downey and noticed the following code at the end of his solution:
if __name__ == '__main__':
                    main(*sys.argv) 

My question focuses on "*sys.argv". how exactly is this supposed to execute? main() is the only function call in the code so i assume that *sys.argv must contain all of the necessary arguments to execute the code. If someone could point me in the right direction, it would be much appreciated.

here is the code:

anagram_sets.py
def signature(s):
    """Returns the signature of this string, which is a string
    that contains all of the letters in order.
    """
    t = list(s)
    t.sort()
    t = ''.join(t)
    return t


def all_anagrams(filename):
    """Finds all anagrams in a list of words.

    filename: string filename of the word list

    Returns: a map from each word to a list of its anagrams.
    """
    d = {}
    for line in open(filename):
        word = line.strip().lower()
        t = signature(word)

        if t not in d:
            d[t] = [word]
        else:
            d[t].append(word)
    return d


def print_anagram_sets(d):
    """Prints the anagram sets in d.

    d: map from words to list of their anagrams
    """
    for v in d.values():
        if len(v) > 1:
            print len(v), v


def print_anagram_sets_in_order(d):
    """Prints the anagram sets in d in decreasing order of size.

    d: map from words to list of their anagrams
    """

    # make a list of (length, word pairs)
    t = []
    for v in d.values():
        if len(v) > 1:
            t.append((len(v), v))

    # sort in ascending order of length
    t.sort()

    # print the sorted list
    for x in t:
        print x


def filter_length(d, n):
    """Select only the words in d that have n letters.

    d: map from word to list of anagrams
    n: integer number of letters

    Returns: new map from word to list of anagrams
    """
    res = {}
    for word, anagrams in d.iteritems():
        if len(word) == n:
            res[word] = anagrams
    return res


if __name__ == '__main__':
    d = all_anagrams('words1.txt')
    print_anagram_sets_in_order(d)

    eight_letters = filter_length(d, 8)
    print_anagram_sets_in_order(eight_letters)



and anagram_db.py:
from anagram_sets import *
import shelve
import sys

def store_anagrams(filename, ad):
    shelf = shelve.open(filename, 'c')
    for word, word_list in ad.iteritems():
        shelf[word] = word_list
    shelf.close()
    
def read_anagrams(filename, word):
    """Looks up a word in a shelf and returns a list of its anagrams.

    filename: string file name of shelf
    word: word to look up
    """
    shelf = shelve.open(filename)
    sig = signature(word)
    try:
        return shelf[sig]
    except KeyError:
        return []
    
def main(name, command='store'):
    if command == 'store':
        ad = all_anagrams('words.txt')
        store_anagrams('anagrams.db', ad)
    else:
        print read_anagrams('anagrams.db', command)

if __name__ == '__main__':
    main(*sys.argv)


Is This A Good Question/Topic? 0
  • +

Replies To: *sys.argv - how does this work?

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2517
  • View blog
  • Posts: 4,001
  • Joined: 21-June 11

Re: *sys.argv - how does this work?

Posted 13 September 2014 - 03:47 PM

The * turns a list into multiple arguments. So if l = [1,2,3], then f(*l) is equivalent to f(1,2,3).

And sys.argv is a list that contains all the command line arguments that you script received.
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6407
  • View blog
  • Posts: 25,884
  • Joined: 12-December 12

Re: *sys.argv - how does this work?

Posted 13 September 2014 - 03:53 PM

    main(*sys.argv)

The asterisk passes a list or tuple (a non-keyword list) as parameters to a function. Two asterisks ** would pass a dictionary.

The function (main) unpacks the command-line arguments are unpacked to the parameters name and command.

How to use *args and **kwargs in Python

This post has been edited by andrewsw: 13 September 2014 - 04:06 PM

Was This Post Helpful? 0
  • +
  • -

#4 rmac362  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 16
  • Joined: 10-September 14

Re: *sys.argv - how does this work?

Posted 13 September 2014 - 03:58 PM

Thank you both for the quick replies and the link. This should get me there. Very helpful.
Was This Post Helpful? 0
  • +
  • -

#5 andrewsw  Icon User is online

  • say what now
  • member icon

Reputation: 6407
  • View blog
  • Posts: 25,884
  • Joined: 12-December 12

Re: *sys.argv - how does this work?

Posted 13 September 2014 - 04:04 PM

sepp2k 's description is more accurate as the splat operator '*' (when used in the above way) expands (unpacks) the list in the function call.

If used in this way:
def someFn(*args):

it is the function that does the unpacking.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1