简体   繁体   English

使用Python执行Shell脚本?

[英]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 - 我的JSON文档jsonStr有一个shell脚本。在反序列化jsonStr之后,我试图使用Python子进程模块执行该shell脚本-

#!/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 - 但是无论如何,只要我运行上面的python脚本,我总是会收到这样的错误-

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. 似乎JSON解析器被“内部”所混淆,尤其是在它说“ hello world”的地方。

Observe that all the JSON escaping rules can be elegantly obtained by just asking the python JSON library for the correct string. 请注意,只需向python JSON库询问正确的字符串,就可以优雅地获得所有JSON转义规则。

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() 你能用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"}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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