Search code examples
pythonargparsesys

How to pass argument that contains regular expression in Python?


I'm using python's argparse module to get arguments from the command line and log in a website, for example: python app.py username password. However, I realized that some more complex passwords may include regular expressions such as '#' or '$', and the args.password will end up being either ignored or modified by the MacOS terminal: python app.py username #pa$$word.

 parser = argparse.ArgumentParser()
 parser.add_argument("username", help="website account username", type=str)
 parser.add_argument("password", help="website account password", type=str)
 args = parser.parse_args()

How can I avoid this behavior without having to hardcode these str arguments?


Solution

  • You are not really talking about regular expressions.

    Further the problem is not python, but your shell.

    you had to call your script with

    python app.py username '#pa$$word'
    

    and sys.argv[2] will contain the password.

    If you have a password containing a single quote ('), then you had to replace it with a triple single quote '\'' where the second ' is prefixed with a \

    As others said already:

    It is considered bad practice to pass passwords as command line arguments to a script as anybody being able to type ps on the same machine will see the password.

    More common options are, that you

    • pass the name of a file containing the password and that this file has no read permission for group and others
    • pass the name of an environment variable containing the password or
    • pipe the password into your script via stdin.
    • prompt for a password. (normally you try to reconfigure the terminal such, that the password will not be displayed on the terminal)