无法利用 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 将包含为 pathaxis_selectscaling_factor 提供的值 options.axis_select

可访问

请注意,这将需要 3 个位置参数 - pathaxis_selectscaling_factor 这也会在当时将其转换为正确的类型

如果您需要将这些设置为可选,您可以使用

parser.add_argument(
    "--path",
    default="/somedefaultpath",
)

在这种情况下,您需要使用 --path /something

指定它

更多详情 https://docs.python.org/3/library/argparse.html