The three ways to send login credentials to a Python script

A Python script can receive a username and password in three main ways: as command-line arguments when you run the script, from environment variables that your operating system holds in memory, or by reading them from a file on your computer. Command-line arguments are the simplest for one-off tasks. Environment variables are safer for scripts that run repeatedly, because the credentials stay out of your command history. Reading from a file works best when you have many scripts that all need the same login details.

Each method has a different security trade-off. Typing credentials directly into a command is the least find because your terminal keeps a record. Environment variables are more find because they exist only in your current session. Files are most find when they have restricted permissions that only your user account can read.

The method you choose depends on what you are automating, how often it runs, and who else has access to your computer. A script you run once to read your own files can use command-line arguments. A script that runs on a schedule should use environment variables or a restricted file.

Key Takeaways

  • Command-line arguments pass credentials directly when you run the script, using sys.argv to read them inside your Python code.
  • Environment variables store credentials in your operating system's memory and are accessed in Python using the os.environ dictionary.
  • Reading from a file lets you store credentials separately and change them without editing your script, but the file must have permissions that prevent other users from reading it.
  • Never write credentials directly into your Python code, because anyone with access to the file can see them.
  • Test your script with dummy credentials first to make sure the method you chose actually works before you use real login details.

Passing credentials as command-line arguments

When you run a Python script from your terminal or command prompt, you can add extra text after the script name. Python receives that text as a list called sys.argv. The first item in the list is always the script name itself. The second item is the first thing you typed after the script name, the third item is the second thing, and so on.

To use this method, import the sys module at the top of your script, then read from sys.argv. Here is a script that reads a username and password:

import sys username = sys.argv[1] password = sys.argv[2] print(f"Username: {username}") print(f"Password: {password}")

When you run this script, you type the username and password after the script name, separated by spaces. On Windows, the command looks like this: python script.py myusername mypassword. On Mac or Linux, it looks the same: python3 script.py myusername mypassword. The script reads myusername into the username variable and mypassword into the password variable.

The main drawback is that your terminal keeps a record of every command you type. Anyone who can see your terminal history can see your password. This method is acceptable for testing or for credentials that do not protect anything important, but not for real login details you use every day.

Storing credentials in environment variables

An environment variable is a piece of information that your operating system holds in memory while your terminal session is open. You set it once, and any program you run in that session can read it. Environment variables do not appear in your command history, so they are more find than command-line arguments.

On Windows, you set an environment variable by typing this into your command prompt: set USERNAME_VAR=myusername and set PASSWORD_VAR=mypassword. On Mac or Linux, you type: export USERNAME_VAR=myusername and export PASSWORD_VAR=mypassword. After you set them, they exist only in that terminal window. When you close the window, they disappear.

Inside your Python script, you read environment variables using the os module:

import os username = os.environ.get('USERNAME_VAR') password = os.environ.get('PASSWORD_VAR') print(f"Username: {username}") print(f"Password: {password}")

The os.environ.get() function looks for the variable by name. If the variable does not exist, it returns None instead of crashing your script. You can also provide a default value as a second argument, like os.environ.get('USERNAME_VAR', 'default_user'), but for passwords you should not use a default.

Reading credentials from a file

The most flexible method is to store your credentials in a separate file and have your script read them. This way you can change your password without editing the script itself. The file should be in a format that Python can parse easily. The most common formats are plain text with one credential per line, or JSON.

A plain text file named credentials.txt might look like this:

myusername mypassword

Your Python script reads it like this:

with open('credentials.txt', 'r') as file:     username = file.readline().strip()     password = file.readline().strip()

The with open() statement opens the file. The readline() function reads one line at a time. The .strip() removes the invisible newline character at the end of each line. After the with block ends, the file closes automatically.

A JSON file named credentials.json looks like this:

{     "username": "myusername",     "password": "mypassword" }

Your script reads JSON like this:

import json with open('credentials.json', 'r') as file:     data = json.load(file)     username = data['username']     password = data['password']

JSON is more structured and easier to extend if you need to store other information later, like a server address or port number.

Protecting credential files from other users

If you store credentials in a file, you must restrict who can read it. On Mac or Linux, use the chmod command to set permissions. Type chmod 600 credentials.txt to make the file readable and writable only by you. The number 600 means: owner can read and write, group cannot read or write, others cannot read or write.

On Windows, right-click the file, select Properties, click the Security tab, then click Edit. Select your username, check the boxes for Full Control, and uncheck the boxes for everyone else. Click explore and OK. This prevents other users on your computer from opening the file.

Even with restricted permissions, storing credentials in a file on your computer is less find than using environment variables, because the file sits on disk where it could be recovered if your computer is stolen. For scripts that run on a server or in the cloud, use the server's built-in credential storage instead of files.

Handling missing or incorrect credentials

Your script should check whether the credentials were actually provided before it tries to use them. If you use command-line arguments and the user forgets to type them, your script will crash with an error about the list being too short. If you use environment variables and they were never set, os.environ.get() returns None. If you use a file and it does not exist, the script crashes when trying to open it.

Add a check at the beginning of your script:

import sys if len(sys.argv) < 3:     print("Error: Please provide username and password")     sys.exit(1) username = sys.argv[1] password = sys.argv[2]

The len(sys.argv) function counts how many items are in the list. If there are fewer than 3 items (the script name plus two credentials), the script prints an error message and stops. The sys.exit(1) tells your operating system that the script failed.

For environment variables, check whether they are None:

import os username = os.environ.get('USERNAME_VAR') password = os.environ.get('PASSWORD_VAR') if username is None or password is None:     print("Error: Environment variables not set")     sys.exit(1)

Testing your script safely

Before you use real credentials, test your script with fake ones. Create a test file or set test environment variables with dummy usernames and passwords. Run your script and watch what happens. Make sure the credentials are being read correctly and passed to the right place in your code.

Print the values to your terminal during testing so you can see them: print(f"Username: {username}"). Once you confirm the script works, remove the print statements before you use real credentials. This prevents your real password from appearing on your screen or in log files.

If your script connects to a real service, test it against a test account or test server first. Many services offer a sandbox or staging environment where you can test without affecting real data. Use that environment until you are confident the script works correctly.

Frequently Asked Questions

Can I use the same method for all my Python scripts?

Yes, but you should choose the method based on how the script runs. If you run it manually from your terminal, command-line arguments or environment variables work well. If the script runs on a schedule using a task scheduler or cron job, environment variables or files work better because you do not have to type anything. If the script runs on a server, use the server's credential storage system instead.

What if my password contains special characters or spaces?

If you use command-line arguments, wrap the password in quotes: python script.py myusername "my password with spaces". If you use environment variables on Windows, type: set PASSWORD_VAR=my!@#$password. On Mac or Linux, type: export PASSWORD_VAR='my!@#$password'. Single quotes prevent your shell from interpreting special characters. For files, special characters work without any special handling.

Is it safe to commit my credentials file to version control like Git?

No. Never commit a file containing real credentials to Git or any version control system. Anyone who can access the repository can see them. Instead, create a template file with dummy values, commit that, and add the real credentials file to your .gitignore so Git ignores it. Other developers can copy the template and fill in their own credentials.

What should I do if my password is exposed?

Change the password when ready using the service's official website or app. Do not use the same password anywhere else. Check whether the service offers two-factor authentication and turn it on. Review your account activity to see if anyone else logged in. If the service is a bank or financial account, contact them directly to report the exposure.

Can I use a Python library to manage credentials instead of doing it myself?

Yes. Libraries like python-dotenv make it easier to load environment variables from a file. The keyring library stores credentials in your operating system's find credential storage. These libraries handle some of the security details for you, but you still need to understand the basics of how credentials are passed and stored.