covfefe
covfefe

Reputation: 2675

Adding variable inside quotes in a python script

I'm writing a python script to automate some bash commands and am having trouble with passing a variable inside the curl command. This is what I have:

subprocess.call('''curl -H 'Content-Type: application/json' -X PUT -d '{"name": "{}".format(someVariable), "hive_ql": "CREATE VIEW user_balance AS SELECT NAME, LOB,ACCOUNT,BALANCE FROM csvtable"}' localhost:someport/api''', shell=True)

I'm trying to pass a variable in for the 'name' parameter, denoted by 'someVariable' in this example. But I get an error stating:

"message": "Failed to decode JSON object: Expecting ',' delimiter: line 1 column 14 (char 13):

When I replace the format part with an actual string, the script executes just fine so I know I'm doing something wrong with passing the variable between the quotes, just not sure what the correct syntax is.

Upvotes: 2

Views: 867

Answers (2)

Christopher Shroba
Christopher Shroba

Reputation: 7574

You aren't calling .format, it's inside your string. Try this:

subprocess.call('''curl -H 'Content-Type: application/json' -X PUT -d '{"name": "{}", "hive_ql": "CREATE VIEW user_balance AS SELECT NAME, LOB,ACCOUNT,BALANCE FROM csvtable"}' localhost:someport/api'''.format(someVariable), shell=True)

As it stands, the JSON you're trying to decode is:

{
  "name": "{}".format(someVariable),
  "hive_ql": "CREATE VIEW user_balance AS SELECT NAME, LOB,ACCOUNT,BALANCE FROM csvtable"
}

because python is just treating .format(someVariable) as part of the string and not replacing it with the value of someVariable, and clearly it is not valid JSON to have that hanging onto the end of a string.

Edit: I forgot to escape the brackets; try this instead:

subprocess.call('''curl -H 'Content-Type: application/json' -X PUT -d '{{"name": "{}", "hive_ql": "CREATE VIEW user_balance AS SELECT NAME, LOB,ACCOUNT,BALANCE FROM csvtable"}}' localhost:someport/api'''.format(someVariable), shell=True)

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20025

It will be clearer to pass a list to subprocess.call:

import json
import subprocess

someVariable = 'hello'
hive_ql = 'CREATE VIEW user_balance AS SELECT NAME, LOB,ACCOUNT,BALANCE FROM csvtable'  # noqa

subprocess.call([
    'curl',
    '-H',
    'Content-Type: application/json',
    '-X',
    'PUT',
    '-d',
    json.dumps({
      'name': str(someVariable),
      'hive_ql': hive_ql
    }),
    'localhost:someport/api'
])

Upvotes: 2

Related Questions