2

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.

2

2 Answers 2

2

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'
])
Sign up to request clarification or add additional context in comments.

4 Comments

When I run this, I get 'curl: try 'curl --help' or 'curl --manual' for more information'
Try removing shell=True
^That worked, thanks! Any idea why that might have been the issue?
Looks like shell=True is only needed if subprocess is calling a single line (as opposed to an array as in this example)
1

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)

1 Comment

When I ran this, I got KeyError: '"name"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.