optparse主函数,如何使用选项

0 投票
1 回答
1002 浏览
提问于 2025-04-18 16:59

我有一个脚本,里面有好几个函数,内容太长不能在这里写出来。不过我在一个主函数里实现了 optparse,这个主函数是:

def main():
    usage = "useage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", type="string", dest="filename", help="Get the name of the cabling file")
    parser.add_option("-i","--imod",dest="modules", help="write the modules in order to get some info",metavar="FILE")
    parser.add_option("-d","--data", type="string", dest="datas",default=True, help="write the options of the Info about a (set of) module(s)")
    parser.add_option("-j","--values", type="string", dest="infor",default=True, help="Modules associated to a(some) value(s)")
    parser.add_option("-k","--common", type="string", dest="common",default=True, help="Values with modules in common")

    (options, args) = parser.parse_args()

    if (options.filename is None):
        parser.error("No cabling filename was given!")


    #Info about modules    
    list1 = options.modules.split(',')
    list2 = options.datas.split(',')

    for i in list1:
        print "For module with DetId\n: %r " % (i)
    for j in ist2: 
        print  "%r is: %r" % (j,MyHVDict[i][j]) 
    if __name__=="__main__":
        main()

这个脚本还有其他一些函数,它们需要用户输入的信息(比如 filename 和在主函数里定义的选项)。那么我该怎么在这些函数里使用我在主函数里定义的选项呢?比如如果所有内容都在主函数外面,我只需要写 options.filenameoptions.modules,每次需要的时候就可以用。但是在主函数里面,我不知道该怎么做。

1 个回答

0

如果你的函数是在主函数里面被调用的,你可以把 options.what_you_need_in_function 作为一个参数传递进去。

def your_funcion(parameter_you_need):
    ...

def main():
    ...
    your_function(options.what_you_need_in_function)
    ...

顺便提一下,optparse 模块已经不再推荐使用了,你可以换成 argparse 模块。

撰写回答