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

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

问题描述

我有问题从argpars调用函数。这是我的脚本的一个简化版本,可以运行,打印我给出的任何值-s或-p

 
导入argparse

def main():

parser = argparse.ArgumentParser(description =您是否希望扫描实况主机或进行端口扫描?)
parser.add_argument( -s,dest ='ip3octets',action ='store',help ='输入C类网络的前三个八位位组以扫描实况主机')
parser.add_argument( - p, dest ='ip',action ='store',help ='进行指定主机的portscan')

args = parser.parse_args()

print args.ip3octets
print args.ip

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

 
import argparse

def main():

parser = argparse.ArgumentParser(description =您是否希望扫描实况主机或进行端口扫描?)
parser.add_argument( - s,dest ='ip3octe ts',action ='store',help ='输入C类网络的前三个八位组来扫描现场主机')
parser.add_argument( - p,dest ='ip',action = 'store',help ='进行指定主机的portscan')

args = parser.parse_args()

printip3octets()
printip()

def printip3octets():

print args.ip3octets

def printip():

print args.ip

if __name__ ==__main __:main()

有人知道我要去哪里吗?非常感谢!

完全相同,请参阅此问题以解释原因。



您有(至少)2个选项:


  1. args 作为参数传递给您的函数
  2. 使 args 一个全局变量。

我不确定如果其他人同意,但我个人认为,如果语句中的所有解析器功能位于内,即main将如下所示:

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

Hey guys, 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? Thanks very much!

解决方案

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

You have (at least) 2 options:

  1. Pass the args as an argument to your function
  2. Make args a global variable.

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天全站免登陆