开发者

Calling functions with argparse [duplicate]

开发者 https://www.devze.com 2023-02-11 21:35 出处:网络
This question already has answers here: How do I get a result (output) from a function? How can I use the result later?
This question already has answers here: How do I get a result (output) from a function? How can I use the result later? (4 answers) Closed 5 months ago.

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. 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)


args is a local variable in main() - you need to pass it as parameter to use it in other functions.

...
printip3octets(args)

def printip3octets(args):

    print args.ip3octets
...
0

精彩评论

暂无评论...
验证码 换一张
取 消