使用 argparse 调用函数 [英] Calling functions with argparse

查看:25
本文介绍了使用 argparse 调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从 argpars 调用函数时遇到问题.这是我的脚本的简化版本,它可以打印我给的任何值 -s 或 -p

I'm having issues calling functions from argpars. This is a simplified version of my script and this works, printing whatever value I give -s or -p

import argparse

def main():

    parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
    parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three octets of the class C network to scan for live hosts')
    parser.add_argument("-p", dest='ip', action='store',help='conduct a portscan of specified host')

    args = parser.parse_args()

    print args.ip3octets
    print args.ip

然而,这对我来说在逻辑上是相同的会产生错误:

This however, which to me is logically identical produces errors:

import argparse

def main():

    parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
    parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three octets of the class C network to scan for live hosts')
    parser.add_argument("-p", dest='ip', action='store',help='conduct a portscan of specified host')

    args = parser.parse_args()

    printip3octets()
    printip()

def printip3octets():

    print args.ip3octets

def printip():

    print args.ip

if __name__ == "__main__":main()

有人知道我哪里出错了吗?

Does anyone know where I am going wrong?

推荐答案

完全相同,参见 这个问题 解释原因.

It is not identical, see this question for explanation why.

您(至少)有两个选择:

You have (at least) 2 options:

  1. args 作为参数传递给您的函数
  2. 使 args 成为一个全局变量.
  1. Pass the args as an argument to your function
  2. Make args a global variable.

我不确定其他人是否同意,但我个人会将所有解析器功能移到 if 语句中,即主要看起来像:

I'm not sure if others agree, but personally I would move all the parser functionality to be inside the if statement, i.e, the main would look like:

def main(args):
    printip3octets(args)
    printip(args)

这篇关于使用 argparse 调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆