【问题标题】:optparse main function, how to use the options insideoptparse主函数,里面的选项怎么用
【发布时间】:2014-10-05 14:29:00
【问题描述】:

我有一个有几个函数的脚本,写在这里太长了,但是我在一个主函数中实现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,只要我需要这个,但在函数内部我不知道该怎么做。

【问题讨论】:

  • 您不能(轻松)从外部main 访问options;如果从main 调用的函数需要访问options,则将整个对象或所需的特定选项作为显式参数传递。
  • 可能是复制粘贴错误,但最后一个块 if __name__ == "__main__": 不应缩进。
  • 那么,我应该在主函数中编写其他函数还是在没有函数的情况下实现 optparse?

标签: python function class main optparse


【解决方案1】:

如果您的函数在 de main 函数中被调用,您可以将 options.what_you_need_in_function 作为参数传递。

def your_funcion(parameter_you_need):
    ...

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

顺便说一句,optparse 模块已弃用,您可以更改为 argparse 模块。

【讨论】:

  • 但是如果我把 main() 函数放在底部,因为有一个输入,例如 your_funcion,后者不会执行,
  • 对不起@marycrant,我不明白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-22
相关资源
最近更新 更多