Reputation: 419
I am curious how to set a variable using optparse. I run the program as such;
programname.py -d c:\users\\etc\etc\etc
I want to be able to use -d C:\Users\\etc\etc to populate a variable called, "path", which I use later in the program. Can this be done? Here is the optionparser code I have.
I call the Path variable later, which I use to populate a dictionary.
Error I get is:
E:>japp_id.py -d "C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\ AutomaticDestinations" Traceback (most recent call last): File "E:\japp_id.py", line 30, in for ids in os.listdir(path): NameError: name 'path' is not defined
try:
import os
import sys
import urllib2
from BeautifulSoup import BeautifulSoup
from optparse import OptionParser
except ImportError:
print 'Imports not installed'
sys.exit()
def main():
usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser()
parser.add_option("-d", "--default", action="callback", type="string", dest="dpath")
(opts, args) = parser.parse_args()
if opts.dpath == None:
parser.print_help()
parser.error("You must supply a -d for dpath")
if not os.path.isfile(opts.dpath):
parser.error("%s does not exist" % opts.dpath)
if __name__ == "__main__":
main()
appIDlist = []
for ids in os.listdir(path):
appid = "%s" % (ids).rstrip('.automaticDestinations-ms')
appIDlist.append(str(appid))
f = urllib2.urlopen("http://www.forensicswiki.org/wiki/List_of_Jump_List_IDs")
s = f.read()
soup = BeautifulSoup(''.join(s))
rows = soup.findAll('tr')
appIDdictionary = dict() #create an empty dictionary to allow lookups {'appID':'processName'}
for tr in rows: #iterate through every row in the table
cols = tr.findAll('td', limit=2) #get the first two data chunks (<td>'s)
appID = str(cols[0]).rstrip('</td>').lstrip('<td>') #clean up formatting
processName = str(cols[1]).rstrip('</td>').lstrip('<td>') #clean up formatting
appIDdictionary[appID] = processName #add the pair to the dictionary
#iterate through list of appids pulled from windows user profile, look them up in the dictionary, and print the result
for id in appIDlist:
if id in appIDdictionary:
print appIDdictionary[id]# + " is " + ids.rstrip('.automaticDestinations-ms')
else:
print 'Unable to find ' + id + ' in dictionary.'
f.close()
Upvotes: 1
Views: 2399
Reputation: 8433
You probably aren't passing it in: you either need to call a function with opts
and access opts.dpath
or do myfunc(opts.dpath)
.
Maybe. Your code doesn't actually show us where the problem is.
UPDATE:
yeah, you want for ids in os.listdir(opts.dpath)
around line 30.
Upvotes: 0
Reputation: 4128
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
The dest
parameter is the name of the variable that your path gets stored to. It is subsequently accessed using opts.filename
.
Upvotes: 1