繁体   English   中英

在python中使用optparse定义变量

[英]Defining a variable with optparse in Python

我很好奇如何使用optparse设置变量。 我这样运行程序;

程序名.py -dc:\\ users \\\\ etc \\ etc \\ etc

我希望能够使用-d C:\\ Users \\\\ etc \\ etc来填充一个名为“ path”的变量,该变量稍后将在程序中使用。 能做到吗? 这是我拥有的optionparser代码。

我稍后调用Path变量,该变量用于填充字典。

我得到的错误是:

E:> japp_id.py -d“ C:\\ Users \\\\ AppData \\ Roaming \\ Microsoft \\ Windows \\ Recent \\ AutomaticDestinations”回溯(最近一次调用为上):文件“ E:\\ japp_id.py”,第30行,用于os.listdir(path)中的id:NameError:名称“ path”未定义

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()

从python docs

parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")

dest参数是路径存储到的变量的名称。 随后使用opts.filename访问它。

您的意思是path = opts.dpath吗?

然后os.listdir(path) ...

您可能没有传递它:您需要使用opts调用一个函数并访问opts.dpath或执行myfunc(opts.dpath)

也许。 您的代码实际上并未向我们显示问题出在哪里。

更新:

是的,您要在第30行附近的for ids in os.listdir(opts.dpath)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM