Suraj
Suraj

Reputation: 195

Unable to pass variable to a bash command in python

I am trying to pass a python variable to a bash command like this:

subscriptionId = "xxxxx"
command = " az account show -s $subscriptionId"
subprocess.check_output(command)

I get there following error:

error : az account show: error: argument --subscription/-s: expected one argument

Upvotes: 2

Views: 212

Answers (2)

issac john
issac john

Reputation: 88

since the variable command is just a string you could simply do this.


subscriptionId = "xxxxx"
command = " az account show -s " + subscriptionId
subprocess.check_output(command)

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114478

Assigning a Python variable like subscriptionId = "xxxxx" does not magically place it in your environment, much less pass it to a subprocess. You need to do that interpolation yourself:

command = f"az account show -s {subscriptionId}"

If you really want to use environment variables, add the variable you want and enable shell expansion:

subscriptionId = ...
env = os.environ.copy()
env['subscriptionId'] = subscriptionId
command = "az account show -s ${subscriptionId}"
subprocess.check_output(command, env=env, shell=True)

Alternatively, you can mess with your own process environment:

subscriptionId = ...
os.environ['subscriptionId'] = subscriptionId
command = "az account show -s ${subscriptionId}"
subprocess.check_output(command, shell=True)

These options are, in my opinion, not recommended, since they raise all the security issues that shell=True brings with it, while providing you with no real advantage.

Upvotes: 1

Related Questions