Reputation: 8312
I have a file that I've made executable. It has a function in it that I would like to return its results to the command line but, I keep getting NameError messages. To break things down, I'm using LinuxMint Lisa and so far I have:
#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
def dictionary(word):
br = mechanize.Browser()
response = br.open('http://www.dictionary.reference.com')
br.select_form(nr=0)
br.form['q'] = word
br.submit()
definition = BeautifulSoup(br.response().read())
trans = definition.findAll('td',{'class':'td3n2'})
fin = [i.text for i in trans]
query = {}
for i in fin:
query[fin.index(i)] = i
return query
print dictionary(sys.argv)
Then I chmod from my terminal:
sudo chmod +x this_file.py
When I call this file from the command-line, I'll enter:
./this_file.py 'pass'(or any other string argument)
Which will return:
TypeError: Must assign a string
So I know I'm obviously not using sys.argv correctly but, I have a feeling like I'm mucking something else up when attempting to return this functions results to the command-line.
Upvotes: 3
Views: 2054
Reputation: 158
The problem with the question as currently posted is that sys.argv is a list, not a string, so when you set the form entry 'q' you are setting it to a list of arguments to the program. You could change the program to pass in the first argument:
print dictionary(sys.argv[1])
Or call the dictionary functions multiple times:
for i in sys.argv[1:]:
print dictionary(i)
Note that we don't want to include the program name itself so omit sys.argv[0].
Upvotes: 1
Reputation: 615
Shouldn't it have been print dictionary(sys.argv[1])
. I guess you want to search the commandline argument in the dictionary.com
Upvotes: 1
Reputation: 143082
Ok, I might as well post this as my answer instead of just a comment:
In
print dictionary(agrv)
argv
is misspelled.
It should be
print dictionary(sys.argv)
Also, use sys.argv
, argv
by itself won't suffice
Upvotes: 3
Reputation: 599748
You don't make it clear what you mean by 'returning' results to the command line. If you just want to print the results, you can do print
.
But the error message you're getting has nothing to do with that. It's caused by two things: one, you've put agrv
instead of argv
. And second, you've imported sys
, so you need to reference sys.argv
not just argv
.
Upvotes: -1
Reputation: 39451
argv is an attribute of the sys
module
Use either
sys.argv
or do
from sys import argv
Upvotes: 2