2

I am running below Python code & using subprocess to call one Python script. It is not able to substitute the value of ${ENVIRONMENT}.

import sys
import subprocess

#ENVIRONMENT=sys.argv[1]
ENVIRONMENT='test'

url=subprocess.check_output("python env.py ${ENVIRONMENT}", shell=True)
Selcuk
  • 57,004
  • 12
  • 102
  • 110
rkj
  • 671
  • 3
  • 14
  • 25

1 Answers1

0

Use string formatting:

url = subprocess.check_output(
    "python env.py {ENVIRONMENT}".format(ENVIRONMENT=ENVIRONMENT), shell=True)

or pass your command as a list:

url = subprocess.check_output(["python", "env.py", ENVIRONMENT])
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Great—now can we tell people to either use environment variables (if there’s some reason for the shell to be aware of them) or (better) avoid the shell entirely? Generating shell commands is just asking for trouble. – Davis Herring Aug 28 '19 at 02:28
  • Well, it is probably a misnomer. If you look at the example it is just a Python variable and not an O/S environment variable. Even the commented out line hints that it's a command line argument. – Selcuk Aug 28 '19 at 02:30
  • I’m saying it’s reasonable to *set* it as an environment variable for use in subprocesses (as for the shell-command syntax in the question), or to use it as an argument to them, but not (usually) to use it as a substring of a shell command. – Davis Herring Aug 28 '19 at 02:48