Prevent expansion of wildcards in non-quoted python script argument when running in UNIX environment

前端 未结 4 341
囚心锁ツ
囚心锁ツ 2021-01-14 20:26

I have a python script that I\'d like to supply with an argument (usually) containing wildcards, referring to a series of files that I\'d like to do stuff with. Example here

4条回答
  •  孤城傲影
    2021-01-14 21:14

    Its not UNIX that is doing the expansion, it is the shell.

    Bash has an option set -o noglob (or -f) which turns off globbing (filename expansion), but that is non-standard.

    If you give an end-user access to the command-line then they really should know about quoting. For example, the commonly used find command has a -name parameter which can take glob constructs but they have to be quoted in a similar manner. Your program is no different to any other.

    If users can't handle that then maybe you should give them a different interface. You could go to the extreme of writing a GUI or a web/HTML front-end, but that's probably over the top.

    Or why not prompt for the filename pattern? You could, for example, use a -p option to indicate prompting, e.g:

    import argparse
    import glob
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', action="store", dest="i")
    parser.add_argument('-p', action="store_true", default=False)
    
    results = parser.parse_args()
    
    if results.p:
        pattern = raw_input("Enter filename pattern: ")
    else:
        pattern = results.i
    
    list_of_matched_files = glob.glob(pattern)
    print list_of_matched_files
    

    (I have assumed Python 2 because of your print statement)

    Here the input is not read by the shell but by python, which will not expand glob constructs unless you ask it to.

提交回复
热议问题