我有一个包含多个函数的脚本,并且在这里写的时间太长了,但我在main函数中实现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
和主函数中定义的选项),那么如何使用我在此main函数中定义的选项,例如,如果一切都在main函数之外,我只需要写options.filename
或options.modules
,我需要这个,但在函数内部我不知道该怎么做。
答案 0 :(得分:0)
如果在de main函数内调用函数,则可以将options.what_you_need_in_function
作为参数传递。
def your_funcion(parameter_you_need):
...
def main():
...
your_function(options.what_you_need_in_function)
...
BTW optparse
模块已弃用,您可以更改为argparse
模块。