How to Pipe Python stdout with xargs

When writing instructions for getting started with Tanzawa, users needed a way to set a unique SECRET_KEY in their environment variable configuration file. Initially I had a secret key entry in the sample file with some instructions to "just modify it". But that felt like I was just passing the buck.

What I wanted to do was to generate a unique secret_key and output it to the .env file. Outputting just the secret key is simple, you can just use >> and append output to an existing file. But I wanted to use my Python secret key output as an argument to another command.

I did it as follows:

python3 -c "import secrets; print(secrets.token_urlsafe())" | xargs -I{} -n1 echo SECRET_KEY={} >> .env

1. Use the Python secrets module to generate a secure token.
2. Pipe the output to xargs.
3. -I is "replace string" and "{}" is the string we want xargs to replace. -n1 limits us to a single argument.
4. xargs executes and takes our Python output as an argument and replaces the {} with it, giving us our desired string.

Writing this now, I probably could have just used Python to include the SECRET_KEY= bit and forgone using xargs, but it was good practice anyways.