使用argparse调用函数

2 投票
2 回答
6943 浏览
提问于 2025-04-16 12:07

我在使用argparse调用函数时遇到了一些问题。这是我脚本的一个简化版本,这个版本可以正常工作,打印出我给的-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 个回答

2

args 是在 main() 函数里面的一个局部变量 - 你需要把它作为参数传递给其他函数,才能在那些函数里使用它。

...
printip3octets(args)

def printip3octets(args):

    print args.ip3octets
...
7

这并不是完全一样的,想了解原因可以看看这个问题

你有(至少)两种选择:

  1. args作为参数传给你的函数
  2. args设为全局变量。

我不确定其他人是否同意,但我个人觉得可以把所有的解析功能放在if语句里面,也就是说,主程序可以这样写:

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

撰写回答