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()
mrwh1t3
  • 349
  • 1
  • 4
  • 13

3 Answers3

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.

JosefAssad
  • 4,018
  • 28
  • 37
  • appIDlist = [] for ids in os.listdir(path): appid = "%s" % (ids).rstrip('.automaticDestinations-ms') appIDlist.append(str(appid)) – mrwh1t3 May 04 '12 at 15:06
  • 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... – JosefAssad May 04 '12 at 15:08
  • 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? – mrwh1t3 May 04 '12 at 15:11
  • 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? – JosefAssad May 04 '12 at 15:16
  • 1
    Then I get the: for ids in os.listdir(opts.path): NameError: name 'opts' is not defined – mrwh1t3 May 04 '12 at 15:20
  • You'll have to show your code then. The opts needs to be passed to the part of the code where you're using it; I'm guessing that isn't happening. – JosefAssad May 04 '12 at 15:21
0

Do you mean path = opts.dpath ?

Then os.listdir(path) ...

jadkik94
  • 7,000
  • 2
  • 30
  • 39
  • Please format it correctly. Where does the `main` function end? – jadkik94 May 04 '12 at 15:20
  • 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. – jadkik94 May 04 '12 at 15:26
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.

quodlibetor
  • 8,185
  • 4
  • 35
  • 48