[英]How can I make command line argument values get assigned to selection of 2 variables in python?
I am using the argparse package here.我在这里使用 argparse package。
There are 4 possible command line arguments in this code.此代码中有 4 个可能的命令行 arguments。 I need to choose any combination of only 2 of them, for example "python script.py -arg1 int1 int2 int3 -arg4 int1 int2 int3" and have those int values assigned to variables in for loops(see below).
我只需要选择其中两个的任意组合,例如“python script.py -arg1 int1 int2 int3 -arg4 int1 int2 int3”,并将这些 int 值分配给 for 循环中的变量(见下文)。
How can I make it so that it doesn't matter which of the 4 command line arguments are input, and their int values get assigned to one of the two for loops?我怎样才能使输入 4 个命令行 arguments 中的哪一个无关紧要,并将它们的 int 值分配给两个 for 循环之一? It doesn't matter which for loop they get into, as long as all combinations are possible.
只要所有组合都是可能的,他们进入哪个 for 循环并不重要。 Does this even make sense?
这甚至有意义吗? Sorry if it doesn't
抱歉,如果没有
import numpy as np
import argparse
parser = argparse.ArgumentParser(description = 'Test')
parser.add_argument('-arg1', nargs =3, required = False, type = int)
parser.add_argument('-arg2', nargs = 3, required = False, type = int)
parser.add_argument('-arg3', nargs = 3, required = False, type = int)
parser.add_argument('-arg4', nargs = 3, required = False, type = int)
args = parser.parse_args()
if arg1:
args.arg1[0] = #start1 or start2
args.arg1[1] = #stop1 or stop2
args.arg1[2] = #num_samples1 or numsamples2
if arg2:
args.arg2[0] = #start1 or start2
args.arg2[1] = #stop1 or stop2
args.arg2[2] = #num_samples1 or numsamples2
if arg3:
args.arg3[0] = #start1 or start2
args.arg3[1] = #stop1 or stop2
args.arg3[2] = #num_samples1 or numsamples2
if arg4:
args.arg4[0] = #start1 or start2
args.arg4[1] = #stop1 or stop2
args.arg4[2] = #num_samples1 or numsamples2
for a in np.linspace(start1, stop1, num_samples1):
for b in np.linspace(start2,stop2,num_samples2):
#do something with these values
First get your two args by iterating over the four possibilities and selecting those that aren't None:首先通过迭代四种可能性并选择那些不是无的来获得你的两个参数:
two_args = [a for a in (args.arg1, args.arg2, args.arg3, args.arg4) if a]
if len(two_args) != 2:
print("Exactly two of arg1, arg2, arg3, and/or arg4 must be provided")
exit()
Then you can get your six values like this:然后你可以得到你的六个值是这样的:
(start1, stop1, num_samples1), (start2, stop2, num_samples2) = two_args
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.