用argparse调用函数
嘿家伙,我有问题从argpars调用函数。 这是我的脚本的一个简化版本,它可以工作,打印我给出的任何值-s或-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
然而,这对我来说在逻辑上是相同的,会产生错误:
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()
有谁知道我要去哪里? 非常感谢!
它不完全相同,请参阅此问题以解释原因。
您有(至少)2个选项:
args作为参数传递给您的函数 args成为全局变量。   我不确定其他人是否同意,但是我个人会将所有解析器功能移到if语句中,即主类似于: 
def main(args):
    printip3octets(args)
    printip(args)
 args是main()中的局部变量 - 您需要将它作为参数传递,以便在其他函数中使用它。 
...
printip3octets(args)
def printip3octets(args):
    print args.ip3octets
...
