1

optparse を使用して変数を設定する方法に興味があります。私はそのようにプログラムを実行します。

programname.py -dc:\users\\etc\etc\etc

-d C:\Users\\etc\etc を使用して、後でプログラムで使用する「パス」という変数を設定できるようにしたいと考えています。これはできますか?これが私が持っているoptionparserコードです。

辞書を作成するために使用する Path 変数を後で呼び出します。

私が得るエラーは次のとおりです。

E:>japp_id.py -d "C:\Users\\AppData\Roaming\Microsoft\Windows\Recent\ AutomaticDestinations" トレースバック (最新の呼び出しが最後): ファイル "E:\japp_id.py"、30 行目、 for os.listdir(path) の ID: NameError: name '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()
4

3 に答える 3

1

python docs から

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

destパラメータは、パスが格納される変数の名前です。その後、 を使用してアクセスしopts.filenameます。

于 2012-05-04T15:03:42.830 に答える
0

あなたはおそらくそれを渡していないでしょう. and で関数を呼び出してoptsアクセスするopts.dpathか、 doする必要がありますmyfunc(opts.dpath).

多分。あなたのコードは実際には問題の場所を示していません。

アップデート:

for ids in os.listdir(opts.dpath)ええ、 30行目あたりが必要です。

于 2012-05-04T15:12:45.857 に答える
0

ということpath = opts.dpathですか?

それからos.listdir(path)...

于 2012-05-04T15:03:36.110 に答える