Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: best way to catch env variables from parsed arguments?

Let say we have a script that accepts arguments, which then dispatches it to subprocess run. When there are no ENV defined, I can simply dispatch all args directly and call commands, like:

import subprocess
import sys

subprocess.run(sys.argv[1:], check=True)

But if I let say call like this my-script.py A=22; B=33; echo "test", then first argument is found as environment variable, not executable.

Is there some good way to recognize when we have ENV before command to handle it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

P.S. I could use Popen with shell=True to propagate it to shell, but I want to preprocess command before executing it (like do extra stuff if I got specific ENV passed etc).

>Solution :

It depends on the shell you use.

When you write:

my-script.py A=22; B=33; echo "test"

It is 3 commands to (for example Bash) shell:

my-script.py A=22
B=33
echo "test"

What you should do, if you want to pass env vars to your script, is:

export B=33
my-script.py A=22
echo "test"

Then your script will receive argument "A=22", and env var B will be available to check in it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading