Mike Girard
Mike Girard

Reputation: 464

Parsing python command line arguments

Complete newbie question.

I am developing a class for searching a movie database using an API.

Here is how you make a query using the movie title and year from within the Python interpreter:

import moviesearch

movie_db = moviesearch.MovieSearch()
result = movie_db.search('Clockwork Orange', year='1971')
print result

Doing this particular query yields one result from the service I am using.

To save typing for testing, I have created the following script m.py:

from sys import argv
import moviesearch

script, movie_name, params = argv

movie_db = moviesearch.MovieSearch()
result = movie_db.search(movie_name, params)
print result

When I execute this script like so:

python m.py 'Clockwork Orange', year='1971'

the service yields two results.

So this means that there is something wrong with the way I am formatting my parameters when I am testing the class with the script. Can someone please tell me what I am doing wrong?

I am not including the class for querying the movie database because I don't think that's necessary for figuring out what's wrong. What I need to know is how to properly format my parameters when using the script so that it executes exactly as it does in the example above where I am using the class directly from the Python interpreter.

Thanks in advance for any help.

Upvotes: 0

Views: 198

Answers (1)

abarnert
abarnert

Reputation: 366123

When you do this in the shell (I'm assuming a *nix platform with an sh-compatible shell; Windows is probably slightly different):

python m.py 'Clockwork Orange', year='1971'

The sys.argv list will be:

['m.py', 'Clockwork Orange,', 'year=1971']

So, when you do this:

script, movie_name, params = argv

You end up with movie_name set to the string 'Clockwork Orange,' (with an extra comma), and params set to the string 'year=1971'. So, your call is ultimately:

result = movie_db.search('Clockwork Orange,', 'year=1971')

This is not the same as:

result = movie_db.search('Clockwork Orange', year='1971')

So, how do you get what you want?

Well, you can parse the params, with code something like this:

params = dict(pair.split('=') for pair in argv[2:])
result = movie_db.search(movie_name, **params)

The first line will give you a dict with {'year': '1971'}. Then you can use the ** syntax to forward that dict as the keyword arguments to the function.

Finally, you should take out the extra comma in the arguments you use to run the script. (You could write code to strip it, but it seems like it's just a typo, so the better fix is to not make that typo.)

Upvotes: 5

Related Questions