简体   繁体   中英

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?

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)

JSON格式错误,应为:

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

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 ur 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

JSON中不允许使用双引号字符(“)。您应使用转义的单引号将其替换,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM