gpt4 book ai didi

python : extract parameters created with argparse

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:07 24 4
gpt4 key购买 nike

我有一个名为 simple_example.py 的文件,其中包含 2 个函数:

# import the necessary packages
import argparse


class simple:

@staticmethod
def func1():

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", help="name of the user", default='host')
ap.add_argument('-num', '--number', required=True, help='choose a number')
args = vars(ap.parse_args())

# display a friendly message to the user
print("Hi there {}, it's nice to meet you! you chose {}".format(args['name'], args['age']))


@staticmethod
def func2():

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", help="name of the user", default='host')
ap.add_argument('-num', '--number', required=True, help='choose a number')
ap.add_argument("-g", "--greet", help="say greetings", default='hello')
args = vars(ap.parse_args())

# display a friendly message to the user
print("{} there {}, it's nice to meet you! you chose {}".format(args['greet'], args['name'], args['age']))

我希望能够从命令行调用 func1() 或 func2(),因此,我从此 link 创建了另一个名为 Pyrun.py 的文件。

# !/usr/bin/env python
# make executable in bash chmod +x PyRun

import sys
import inspect
import importlib
import os


if __name__ == "__main__":
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)

# get the second argument from the command line
methodname = sys.argv[1]

# split this into module, class and function name
modulename, classname, funcname = methodname.split(".")

# get pointers to the objects based on the string names
themodule = importlib.import_module(modulename)
theclass = getattr(themodule, classname)
thefunc = getattr(theclass, funcname)

# pass all the parameters from the third until the end of what the function needs & ignore the rest
args = inspect.getargspec(thefunc)

print(args)

但是,ArgSpec(args=[], varargs=None, keywords=None, defaults=None) 中的 args 显示空列表。

  1. 如何从 func1 或 func2 中提取参数?

  2. 是否有更好的方法从命令行运行 func1 或 func2?

最佳答案

您可能想使用 sub-commands 。这是使用子命令的示例的实现。

import argparse

def func1(args):

print("Hi there {}, it is nice to meet you! You chose {}.".format(args.name, args.number))

def func2(args):

print("{} there {}, it is nice to meet you! You chose {}.".format(args.greet, args.name, args.number))

#
# The top-level parser
#
parser = argparse.ArgumentParser('top.py', description='An example sub-command implementation')

#
# General sub-command parser object
#
subparsers = parser.add_subparsers(help='sub-command help')

#
# Specific sub-command parsers
#
cmd1_parser = subparsers.add_parser('cmd1', help='The first sub-command')
cmd2_parser = subparsers.add_parser('cmd2', help='The second sub-command')

#
# Assign the execution functions
#
cmd1_parser.set_defaults(func=func1)
cmd2_parser.set_defaults(func=func2)

#
# Add the common options
#
for cmd_parser in [cmd1_parser, cmd2_parser]:
cmd_parser.add_argument('-n', '--name', default='host', help='Name of the user')
cmd_parser.add_argument('-num', '--number', required=True, help='Number to report')

#
# Add command-specific options
#
cmd2_parser.add_argument('-g', '--greet', default='hello', help='Greeting to use')

#
# Parse the arguments
#
args = parser.parse_args()

#
# Invoke the function
#
args.func(args)

示例输出:

$ python ./top.py cmd1 -n Mark -num 3    
Hi there Mark, it is nice to meet you! You chose 3.

$ python ./top.py cmd2 -n Bob -num 7 -g Hello
Hello there Bob, it is nice to meet you! You chose 7.

当然,帮助功能适用于每个子命令。

$ python ./top.py cmd2 -h

usage: top.py cmd2 [-h] [-n NAME] -num NUMBER [-g GREET]

optional arguments:
-h, --help show this help message and exit
-n NAME, --name NAME Name of the user
-num NUMBER, --number NUMBER
Number to report
-g GREET, --greet GREET
Greeting to use

关于 python : extract parameters created with argparse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49311085/

24 4 0