python argparser使用nargs捕获单个选项的冒号分隔输入

时间:2019-01-17 17:38:59

标签: python

我在传输脚本上有下面的代码来捕获源和目标,我可以使用下面的cod来成功获得这样的输入

System.Threading.Thread.Sleep(5000)

但我想更改输入内容。

python program -s "source host" "source folder" -d "destination host" "destination folder"

下面是我用来获取输入的代码

python program -s "source host:source folder" -d "destination host:destination folder"

我该如何做到这一点。请建议

2 个答案:

答案 0 :(得分:1)

您可以只接受1个参数,然后除以:

my_parser = argparse.ArgumentParser(description='To sync files between source and destination')
my_parser.add_argument('-s', "--source", help='Enter the source server detail and source folder name')
my_parser.add_argument('-d', '--destination',  help="Enter the destination server detail")
if len(sys.argv) == 1:
    my_parser.print_help(sys.stderr)
    sys.exit(1)
clarg = my_parser.parse_args()
print(clarg.source.split(":")[0])
print(clarg.source.split(":")[1])
print(clarg.destination.split(':')[0])
print(clarg.destination.split(':')[1])

python program -s "source host:source folder" -d "destination host:destination folder"的输出

source host
source folder
destination host
destination folder

答案 1 :(得分:1)

我认为nargs是错误的工具。相反,您需要进一步处理该参数以产生正确的主机和文件夹。您可以使用type参数设置自定义函数:

import argparse

def host_and_folder(arg):
    try:
        host, folder = arg.split(":")
    except ValueError:
        raise argparse.ArgumentError(None, "Source and Destination details must be in the format host_name:folder_name")
    if not folder:
        folder = "."
    return host, folder

my_parser = argparse.ArgumentParser(description='To sync files between source and destination')
my_parser.add_argument('-s',"--source", help='Enter the source server detail and source folder name', required=True, type=host_and_folder)
my_parser.add_argument('-d', '--destination', help="Enter the destination server detail", required=True, type=host_and_folder)

clarg = my_parser.parse_args()

或者,您也可以指定自定义操作,并将hostfolder分别设置为sourcedestination的属性:

class HostAndFolderAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        try:
           host, folder = values.split(":")
        except ValueError as e:
           parser.error(f"{self.dest.title()} details must be in the format host_name:folder_name")
        setattr(namespace, self.dest, argparse.Namespace(host=host, folder=folder or "."))

my_parser = argparse.ArgumentParser(description='To sync files between source and destination')
my_parser.add_argument('-s',"--source", help='Enter the source server detail and source folder name', required=True, action=HostAndFolderAction, metavar='SOURCE_HOST:[DIRECTORY]')
my_parser.add_argument('-d', '--destination', help="Enter the destination server detail", required=True, action=HostAndFolderAction, metavar='DESTINATION_HOST:[DIRECTORY]')

clarg = my_parser.parse_args(["-s", "foo:temp", "-d", "bar:"])
print(clarg.source.host)
# foo
print(clarg.destination.folder)
# .

clarg = my_parser.parse_args(["-s", "foo:temp", "-d", "bar"])
# usage: ipython3 [-h] -s SOURCE_HOST:[DIRECTORY] -d DESTINATION_HOST:[DIRECTORY]
# error: Destination details must be in the format host_name:folder_name