Search code examples
pythonvariablescommandline

Python script - how to pass password as variable from command line arguments


I am running a REST call using python to generate a access token. The REST call payload has password value. I dont want to hardcode the password there but pass it as an option while running the python script. Below is the payload inside the python script.

payload = "grant_type=client_credentials&client_id=userid&client_secret=password&scope=AppIdClaimsTrust&intent=RequestLink"

Currently I exectute the script by python script.py


Solution

  • Set the token as an environment variable:

    $ export TOKEN=XXXXXXX

    Then using the os library:

    #!/usr/bin/env python
    import os
    
    token = os.environ['TOKEN'] 
    
    

    Use token where you would normally hard code it into your script.

    Alternatively, you could pass it as a command line argument.

    $ python script.py XXXXXXXX
    

    In your script, access the token using:

    #!/usr/bin/env python
    import sys
    
    if len(sys.argv) > 1:
        token = sys.argv[1]
    else:
        print("No token passed")