使用 Python 的 optparse 定义变量

2024-10-01 15:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在程序名.py-d c:\users\\etc\etc\etc

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

我稍后调用Path变量,用它来填充字典。在

我得到的错误是:

E:>;日本_身份证-d“C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\ 自动评估” 回溯(最近一次呼叫): 文件“E:\japp_身份证“,第30行,英寸 对于中的ID操作系统列表目录(路径): 名称错误:未定义名称“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()

Tags: thepathinimportparserfordictionaryif
3条回答

你是说path = opts.dpath?在

然后os.listdir(path)。。。在

From the python docs

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

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

您可能没有传递它:您需要使用opts调用函数并访问opts.dpath或do{}。在

也许吧。你的代码并没有告诉我们问题出在哪里。在

更新:

是的,你想在30号线附近。在

相关问题 更多 >

    热门问题