我很好奇如何使用 optparse 设置变量。我这样运行程序;
程序名.py -dc:\users\\etc\etc\etc
我希望能够使用 -d C:\Users\\etc\etc 来填充一个名为“path”的变量,我稍后会在程序中使用它。这可以做到吗?这是我拥有的选项解析器代码。
我稍后调用 Path 变量,我用它来填充字典。
我得到的错误是:
E:>japp_id.py -d "C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\ AutomaticDestinations" Traceback(最近一次调用最后一次):文件“E:\japp_id.py”,第 30 行,用于os.listdir(path) 中的 ids: 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()