[Python] How to prevent unescaped program arguments

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    This test program parses a single text argument, which could be a URL:

    #!/usr/bin/env python

    import argparse

    def parse_input():
    parser = argparse.ArgumentParser(
    description='Program description'
    )
    parser.add_argument('input_text', type=str, help='A string')
    args = parser.parse_args()

    return args.input_text



    if __name__ == '__main__':
    text = parse_input()
    print(f"Input text: \"{text}\"")


    And of course a URL could have a querystring.

    If the program is called with a quoted argument, nothing bad happens:

    $ ./test.py "sometext?somearg=someval&somearg2=someval2"
    Input text: "sometext?somearg=someval&somearg2=someval2"


    But if someone forgets to quote the argument, this happens:

    $ ./test.py sometext?somearg=someval&somearg2=someval2
    [1] 5174
    $ Input text: "sometext?somearg=someval"
    ^C
    [1]+ Done ./test.py sometext?somearg=someval


    The console waited forever so I had to press Ctrl+C at line 3. I don't really understand what was going on with this wait, but I think that because of the & character in the unescaped argument, Bash executes ./test.py sometext?somearg=someval in background, and immediately executes somearg2=someval2 in foreground, which just assigns a session variable in the shell. For every additional querystring parameter bash would launch them as commands in background. Now imagine if by chance one of those potentially many querystring parameter had no value (as in &somearg3), which are perfectly valid. Also if by chance that unvalued parameter name was the same as some binary in the system, very bad things could happen.

    Can we do something to prevent the user from inadvertedly entering an unquoted argument? So far argparse gives me the exact same result regardless of whether the argument was quoted or unquoted.

    Continue reading...

Compartilhe esta Página