使用Python中的命令行参数调用另一个库函数

时间:2015-11-25 08:18:46

标签: python-2.7 arguments parameter-passing

我试图根据输入的命令行参数调用不同的库函数。

我的main函数将接受输入参数,并将根据传递给cli的参数调用该函数。这是我的主要功能。

from lib.updatefeed import *
    def main():
    ......
    ......
    parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
    if args.update:
        gather(args.update)

    if __name__ == '__main__':
        main()

这里,gather()是我已经在主程序中导入的另一个python库中的另一个函数。

这是带有gather()函数的导入库的主体

def gather(self):
    if not os.path.exists('intel'):
        os.mkdir('intel')
    print "Starting update process"
    counter = 0
    ioc_list = []
    timestr = time.strftime("%Y%m%d-%H%M%S")
    for source in IP.iteritems():
        print source
        name = source + timestr
        print name
        file = open(name, 'w')
        c = connect(source,params=url_param())
        for line in c:
            if line.startswith("/") or line.startswith('\n') or line.startswith("#"):
                pass
            else:
                file.write(line+'\n')

因此当将“-update”参数传递给命令行时,将调用我的gather()函数。 gather()函数的功能是创建一个名为“intel”的目录。 然后,它将遍历IP列表并根据IP和时间戳创建文件名。然后,它将调用connect函数以创建到IP的HTTP连接。 它将解析IP的内容并将其写入文件。

我无法通过使用我在此处添加的程序来实现此目的。 由于某种原因,来自main()函数本身的调用没有成功。 我尝试在gather()函数中添加“print”语句,以查看哪些部分正在工作。 请社区帮助我。

1 个答案:

答案 0 :(得分:0)

这个问题的解决方案在于论证特征。通过定义parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')我认为One参数将与-update参数一起传递给命令行。 但我只关心-update arg在命令行中出现而没有任何其他实体。 这可以通过将脚本行更改为:

来克服
parser.add_argument('-update', action='store_true', help='Update the local storage')

这将确保只有-update的存在才会调用函数“gather()”。