【问题标题】:Unable to utilize sys args to modify variables [duplicate]无法利用 sys args 修改变量 [重复]
【发布时间】:2020-10-26 23:52:41
【问题描述】:

我正在尝试根据程序参数更改一些变量。

这是我的代码:

#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 为例。

【问题讨论】:

    标签: python arguments


    【解决方案1】:

    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])
    

    【讨论】:

      【解决方案2】:

      您可以为此使用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

      【讨论】:

        猜你喜欢
        • 2016-03-22
        • 1970-01-01
        • 2015-10-01
        • 2011-04-09
        • 2020-06-23
        • 2018-10-29
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多