无法利用 sys args 修改变量
Unable to utilize sys args to modify variables
我正在尝试根据程序参数更改一些变量。
这是我的代码:
#initialize all scaling factors to 1
x_scale = 1
y_scale = 1
z_scale = 1
#the second argument is the axis to scale (1-3)
axis_Select = (sys.argv[2])
#the third argument is the scaling factor
scaling_Factor = (sys.argv[3])
if axis_Select == 1:
x_scale = scaling_Factor
elif axis_Select == 2:
y_scale = scaling_Factor
elif axis_Select == 3:
z_scale = scaling_Factor
然后我调用程序:
python3 testScript.py /home/user/Desktop/file.extenstion 2 2
然后如果我做 print(y_scale)
,它是 1
,而不是应该的 2
。
这也适用于其他组合,我只是以 y_scale
为例。
sys.argv
的元素是字符串,需要先转为整数再与整数比较
#the second argument is the axis to scale (1-3)
axis_Select = int(sys.argv[2])
#the third argument is the scaling factor
scaling_Factor = int(sys.argv[3])
你可以使用 argparse
来完成这个
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"path", type=str, help="file path")
parser.add_argument(
"axis_select",
type=int)
parser.add_argument(
"scaling_factor",
type=int)
options = parser.parse_args()
options
将包含为 path
、axis_select
、scaling_factor
提供的值
options.axis_select
等
可访问
请注意,这将需要 3 个位置参数 - path
、axis_select
、scaling_factor
这也会在当时将其转换为正确的类型
如果您需要将这些设置为可选,您可以使用
parser.add_argument(
"--path",
default="/somedefaultpath",
)
在这种情况下,您需要使用 --path /something
指定它
我正在尝试根据程序参数更改一些变量。
这是我的代码:
#initialize all scaling factors to 1
x_scale = 1
y_scale = 1
z_scale = 1
#the second argument is the axis to scale (1-3)
axis_Select = (sys.argv[2])
#the third argument is the scaling factor
scaling_Factor = (sys.argv[3])
if axis_Select == 1:
x_scale = scaling_Factor
elif axis_Select == 2:
y_scale = scaling_Factor
elif axis_Select == 3:
z_scale = scaling_Factor
然后我调用程序:
python3 testScript.py /home/user/Desktop/file.extenstion 2 2
然后如果我做 print(y_scale)
,它是 1
,而不是应该的 2
。
这也适用于其他组合,我只是以 y_scale
为例。
sys.argv
的元素是字符串,需要先转为整数再与整数比较
#the second argument is the axis to scale (1-3)
axis_Select = int(sys.argv[2])
#the third argument is the scaling factor
scaling_Factor = int(sys.argv[3])
你可以使用 argparse
来完成这个
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"path", type=str, help="file path")
parser.add_argument(
"axis_select",
type=int)
parser.add_argument(
"scaling_factor",
type=int)
options = parser.parse_args()
options
将包含为 path
、axis_select
、scaling_factor
提供的值
options.axis_select
等
请注意,这将需要 3 个位置参数 - path
、axis_select
、scaling_factor
这也会在当时将其转换为正确的类型
如果您需要将这些设置为可选,您可以使用
parser.add_argument(
"--path",
default="/somedefaultpath",
)
在这种情况下,您需要使用 --path /something