【发布时间】: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.filename或options.modules,只要我需要这个,但在函数内部我不知道该怎么做。
【问题讨论】:
-
您不能(轻松)从外部
main访问options;如果从main调用的函数需要访问options,则将整个对象或所需的特定选项作为显式参数传递。 -
可能是复制粘贴错误,但最后一个块
if __name__ == "__main__":不应缩进。 -
那么,我应该在主函数中编写其他函数还是在没有函数的情况下实现 optparse?
标签: python function class main optparse