Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python argparser使用nargs为单个选项捕获冒号分隔的输入_Python - Fatal编程技术网

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

python argparser使用nargs为单个选项捕获冒号分隔的输入,python,Python,我有下面的代码在一个转移脚本捕获源和目的地,我能够成功地获得这样的输入使用下面的代码 python程序-s“源主机”“源文件夹”-d“目标主机”“目标文件夹” 但我想改变我的输入像这样的东西 python程序-s“源主机:源文件夹”-d“目标主机:目标文件夹” 下面是我用来获取输入的代码 my_parser=argparse.ArgumentParser(description='To sync files between source and destination') my_parser.a

我有下面的代码在一个转移脚本捕获源和目的地,我能够成功地获得这样的输入使用下面的代码

python程序-s“源主机”“源文件夹”-d“目标主机”“目标文件夹”

但我想改变我的输入像这样的东西

python程序-s“源主机:源文件夹”-d“目标主机:目标文件夹”

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

my_parser=argparse.ArgumentParser(description='To sync files between source and destination')
my_parser.add_argument('-s',"--source", nargs=2,  help='Enter the source server detail and source folder name')Q
my_parser.add_argument('-d', '--destination', nargs=2,  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()

我怎样才能做到这一点。请建议

您只需接受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程序-s“源主机:源文件夹”-d“目标主机:目标文件夹”的输出


您可以只接受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程序-s“源主机:源文件夹”-d“目标主机:目标文件夹”的输出


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

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()
或者,您也可以指定自定义操作,并将
主机
文件夹
分别设置为
目标
的属性:

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

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

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()
或者,您也可以指定自定义操作,并将
主机
文件夹
分别设置为
目标
的属性:

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

谢谢你的建议,我会试试的。谢谢你的建议,我会试试的。