How do you protect yourself from missing comma in vertical string list in python?

前端 未结 4 692
春和景丽
春和景丽 2021-01-12 04:07

In python, it\'s common to have vertically-oriented lists of string. For example:

subprocess.check_output( [
  \'application\',
  \'-first-flag\',
  \'-secon         


        
相关标签:
4条回答
  • 2021-01-12 04:26

    maybe for this particular case:

    arglist = 'application -first-flag -second-flag -some-additional-flag'
    arglist = arglist.split()
    subprocess.check_output(arglist)
    

    Or if you find yourself writing many unique lists like this make a macro that concatenates lines into a list form, so you avoid manually putting the comma.

    0 讨论(0)
  • 2021-01-12 04:27

    Here's another alternative:

    subprocess.check_output('''
    application
    -first-flag
    -second-flag
    -some-additional-flag
    '''.split())
    

    Let Python insert the commas for you, this is especially useful for long lists of strings in configuration files

    0 讨论(0)
  • 2021-01-12 04:30

    You can have commas at the end of a line after whitespace, like this:

    subprocess.check_output( [
       'application'           ,
       '-first-flag'           ,
       '-second-flag'          ,
       '-some-additional-flag' ,
    ] )
    

    Doing it that way looks a little worse, but it is easy to spot if you have missed any arguments.

    0 讨论(0)
  • 2021-01-12 04:35

    You could wrap each string in parens:

    subprocess.check_output( [
      ('application'),
      ('-first-flag'),
      ('-second-flag'),
      ('-some-additional-flag'),
    ] )
    

    And btw, Python is fine with a trailing comma, so just always use a comma at the end of the line, that should also reduce errors.

    0 讨论(0)
提交回复
热议问题