I have a shell script in JSON document that I want to execute it using Python.
Below is my JSON document -
{"script":"#!/bin/bash echo Hello World"}
I will deserialize the above JSON document and extract the script portion of it which is actual shell script and then I need to execute that shell script from the Python. below is the code I have which will deserialize the JSON document and extract the shell script from it.
#!/usr/bin/python
import json
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']
Now how to execute that shell script from the Python in the same code? And after executing the above shell script, it should echo Hello World
Update:- This is what I have tried but it doesn't work after adding a new line to shell script -
#!/usr/bin/python
import subprocess
import json
jsonStr = '{"script":"#!/bin/bash echo Hello World \n"}'
j = json.loads(jsonStr)
print j['script']
print "start"
subprocess.call(j['script'], shell=True)
print "end"
Below is the error I get -
Traceback (most recent call last):
File "shelltest.py", line 8, 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: Invalid control character at: line 1 column 40 (char 40)