简体   繁体   English

如何将未定义数量的可选参数/参数传递给 python 3 脚本

[英]How to pass a undefined number of optional parameters/arguments to a python 3 script

I need to pass 3 obligatory parameters when executing a python script but the program also can receive a undefined number of paramters always greater than 3 for example我需要在执行 python 脚本时传递 3 个强制参数,但程序也可以接收未定义数量的参数,例如总是大于 3

my_prgoram.py 1 2 3 4 5 6

and also并且

my_prgoram.py 1 2 3 4 

I'm trying to do this with the argparse module so far I have this到目前为止,我正在尝试使用argparse模块执行此操作

import argparse

if __name__ == '__main__':
    # Initialize the parser
    parser = argparse.ArgumentParser(
        description="how to run the script: [my_prgoram.py 3 4 5 7 [n]... ] 
    )

# Add the positional parameter
parser.add_argument('first', help="number of cards")
parser.add_argument('cvaluen1', type=int, help="the first value")
parser.add_argument('cvaluen2', type=int, help="the second value")

# Parse the arguments
arguments = parser.parse_args()

# Finally print the passed string
print(arguments.first)
print(arguments.cvaluen1)
print(arguments.cvaluen2)

It might be easier to use argv instead of argparse and it will also be more portable: 使用argv代替argparse可能会更容易,并且它也将更加可移植:

import sys

num_args = len(sys.argv)
if num_args  >= 4:
   first_arg = sys.argv[1]
   second_arg = sys.argv[2]
   third_arg = sys.argv[3]
   if num_args > 4:
      other_args = [arg for arg in args[4:]]

ArgumentParser.parse_known_args() might be of help: ArgumentParser.parse_known_args()可能会有所帮助:

>>> parser.parse_known_args('1 2 3 4 5 6'.split(' '))
(Namespace(cvaluen1=2, cvaluen2=3, first='1'), ['4', '5', '6'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM