user2467545
user2467545

Reputation:

Execute shell script using Python?

I have a shell script in my JSON document jsonStr.. I am trying to execute that shell script using Python subprocess module after deserializing the jsonStr -

#!/usr/bin/python

import subprocess
import json

jsonStr = '{"script":"#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n"}'
j = json.loads(jsonStr)

print "start"
subprocess.call(j['script'], shell=True)
print "end"

But somehow whenever I run my above python script, I always get an error like this -

Traceback (most recent call last):
  File "shellscript", line 27, in <module>
    j = json.loads(jsonStr)
  File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 34 (char 34)

Any thoughts what wrong I am doing here?

Upvotes: 1

Views: 445

Answers (4)

carlosdc
carlosdc

Reputation: 12152

It seems the JSON parser is being confused by a " inside a ", particularly where it says hello world.

Observe that all the JSON escaping rules can be elegantly obtained by just asking the python JSON library for the correct string.

import json
jsoncnt = {'script':'#!/bin/bash \n STRING="Hello World" \n echo $STRING \n'}
jsonStr = json.dumps(jsoncnt)
print jsonStr
q = json.loads(jsonStr)

Upvotes: 2

Pekka
Pekka

Reputation: 2280

Double quote character (") is not allowed inside JSON. You should substitute it with escaped single quote like this:

jsonStr = '{"script":"#!/bin/bash \\n STRING=\'Hello World\' \\n echo $STRING \\n"}'

Upvotes: 1

Vb407
Vb407

Reputation: 1707

It is woking fine for me..

import subprocess
import json

json_dict = {"script":'#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n'}

dump = json.dumps(json_dict)

j = json.loads(dump)

print j
print j['script']

print "start"
subprocess.call(j['script'], shell=True)
print "end"

can you please paste code How u r using json.dumps()

Result:

{u'script': u'#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n'}
#!/bin/bash \n STRING="Hello World" \n echo $STRING \n
start
end

Upvotes: 2

wcp
wcp

Reputation: 126

Wrong JSON format.It should be:

jsonStr = '{"script":"#!/bin/bash \\n STRING=\\"Hello World\\" \\n echo $STRING \\n"}'

Upvotes: 1

Related Questions