如何将已解析语句的列表转换为可以在if语句中使用的列表或字符串?

我正在使用https://github.com/tensorflow/models/blob/master/tutorials/image/imagenet/classify_image.py上的教程imagenet图片识别代码

我设法使所有功能正常运行,但是我想知道如何在末尾以列表或字符串而不是解析的参数的形式获取参数,因此我可以在命令中使用常规的if。

def main(_):
  maybe_download_and_extract()
  image = (flaGS.image_file if flaGS.image_file else
           os.path.join(flaGS.model_dir,'cropped_panda.jpg'))
  run_inference_on_image(image)


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # classify_image_graph_def.pb:
  #   Binary representation of the GraphDef protocol buffer.
  # imagenet_synset_to_human_label_map.txt:
  #   Map from synset ID to a human readable string.
  # imagenet_2012_challenge_label_map_proto.pbtxt:
  #   Text representation of a protocol buffer mapping a label to synset ID.
  parser.add_argument(
      '--model_dir',type=str,default='/tmp/imagenet',help="""\
      Path to classify_image_graph_def.pb,imagenet_synset_to_human_label_map.txt,and
      imagenet_2012_challenge_label_map_proto.pbtxt.\
      """
  )
  parser.add_argument(
      '--image_file',default='',help='Absolute path to image file.'
  )
  parser.add_argument(
      '--num_top_predictions',type=int,default=5,help='Display this many predictions.'
  )
  #how do i get a variable that i can interact with from this

  flaGS,unparsed = parser.parse_known_args()
  tf.app.run(main=main,argv=[sys.argv[0]] + unparsed)

我完全没有解析经验,因此将不胜感激。

afeijian 回答:如何将已解析语句的列表转换为可以在if语句中使用的列表或字符串?

编辑

在我看过ArgumentParser的评论之后。如果插入方法parser.parse_args,则会返回一个名称空间。现在,您可以访问其属性,并且可以获取用户传递的值。

#Every parameter can be accessed using namespace.parameter_name,for example
# with namepsace.model_dir,and you get the string inserted by the user

namespace = parser.parse_args()
if namespace.verbose:
    print("Verbose: ",+ str(verbose))

如果要迭代所有属性,可以使用THIS POST中所述的字典。从字典传递到列表很容易。


旧答案

对于解析输入参数,我使用getopt。很难理解的是如何指定参数和可选参数,但这并不困难。

getopt将返回一个参数列表,您可以在其上迭代和应用条件。 (请参阅getopt documentation for python 3.7.5,也可用于python 3.6和2)。我举一个例子:

def main():
    options,remainder = getopt.getopt(sys.argv[1:],'tci:',['train','classify','id'])
    for opt,arg in options:
        #This is a bool optional parameter
        if opt in ('-t','--train'):
            train = True

        #This is a bool optional parameter
        elif opt in ('-c','--classify'):
            predict = True

        #This is an integer required parameter
        elif opt in ('-i','--id'):
            id= arg

    if train:
        funtion1()
    elif predict:
        function2(id)

if __name__ == '__main__':
    main()

文档说:

  

getopt.getopt(args,shortopts,longopts = [])   解析命令行选项和参数列表。 args是要解析的参数列表,没有对正在运行的程序的前导引用。通常,这意味着sys.argv[1:] shortopts 是脚本要识别的选项字母字符串,其中的选项需要参数,后跟冒号(“:”;即与Unix相同的格式getopt()使用)。 longopts (如果已指定)必须是一个字符串列表,其中包含应支持的long选项的名称。选项名称中不应包含前导“-”字符。需要参数的长选项应后跟等号('=')。

请注意,用户可以将他想要的任何内容用作参数,因此您需要检查它是否正确。

本文链接:https://www.f2er.com/2953349.html

大家都在问