1

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()
1
  • So this is my final code. Let me know where you think. Commented May 20, 2012 at 8:53

3 Answers 3

1

From the python docs:

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.

Sign up to request clarification or add additional context in comments.

6 Comments

appIDlist = [] for ids in os.listdir(path): appid = "%s" % (ids).rstrip('.automaticDestinations-ms') appIDlist.append(str(appid))
Parsing the user input in opts.filename is a separate issue from capturing it from the command line. I don't quite see where you're going with these two comments...
Well, I want -d path_specified to fill the "ids in os.listdir(path)". Specifically the path variable so the user when running the program can specify their own path each time. Make sense?
Hm. Well then it's just a matter of using for ids in os.listdir(opts.path): instead of for ids in os.listdir(path):. Like I said in the answer, `` contains the path that was provided on the command line. What am I missing?
Then I get the: for ids in os.listdir(opts.path): NameError: name 'opts' is not defined
|
0

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.

Comments

0

Do you mean path = opts.dpath ?

Then os.listdir(path) ...

2 Comments

Please format it correctly. Where does the main function end?
It seems that opts is defined inside of the main function and the rest is happening outside. So, either set opts a global variable, or do the whole thing inside the main function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.