【问题标题】:Issue calling another library function using command line argument in Python在 Python 中使用命令行参数调用另一个库函数的问题
【发布时间】:2015-11-25 08:18:46
【问题描述】:

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

我的主函数将接受输入参数,并根据传递给 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()函数将被调用。 collect() 函数的功能是创建一个名为“intel”的目录。 然后它将遍历 IP 列表并根据 IP 和时间戳创建文件名。然后它将调用 connect 函数来创建到 IP 的 HTTP 连接。 它将解析IP的内容并将其写入文件。

我无法通过使用我在此处添加的程序来实现这一点。 由于某种原因,来自 main() 函数本身的调用没有成功。 我尝试在gather() 函数中添加“打印”语句以查看哪些部分正在工作。 社区可以帮我解决这个问题吗?

【问题讨论】:

  • 能否请您在代码示例中包含导入行?
  • 您在上面粘贴的哪一行出现错误?错误信息是什么?
  • @jhinghaus : 添加了 import "from lib.updatefeed import *" where updatefeed.py 在包含gather() 函数的库中。
  • @barny 我添加的代码没有错误。当参数传递给 main 时,它只是不调用gather() 函数。
  • 打印 args.update 会得到什么?在'if args.update:'行之前打印它

标签: python-2.7 arguments parameter-passing


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2015-08-20
    • 2017-01-08
    • 2015-11-02
    • 2017-06-08
    • 1970-01-01
    • 2021-09-03
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多