【发布时间】:2013-12-28 00:50:25
【问题描述】:
我正在尝试使用子进程模块在 Python 中执行 shell 脚本。
下面是我的shell脚本,称为testing.sh。
#!/bin/bash
hello=$jj1
echo $hello
echo $jj1
echo $jj2
for el1 in $jj3
do
echo "$el1"
done
for el2 in $jj4
do
echo "$el2"
done
现在我正在尝试在 Python 中执行上面的 shell 脚本,所以我这样做了 -
subprocess.call(['./testing.sh'])
而且效果很好。现在我正在考虑将上述脚本添加到这样的 JSON 文档中,然后执行它 -
json_script = '{"script":"above testing.sh script here"}'
j = json.loads(json_script)
shell_script = j['script']
subprocess.call(shell_script, shell=True)
但每次我尝试时,它都会给我一个错误 -
下面是我的完整 Python 脚本,它在 JSON 文档中包含上述 testing.sh shell 脚本 -
#!/usr/bin/python
import subprocess
import json
import socket
import os
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
jj = json.loads(jsonData)
print jj['pp']
print jj['sp']
os.putenv( 'jj1', 'Hello World 1')
os.putenv( 'jj2', 'Hello World 2')
os.putenv( 'jj3', ' '.join( str(v) for v in jj['pp'] ) )
os.putenv( 'jj4', ' '.join( str(v) for v in jj['sp'] ) )
print "start"
jsonDataaa = '{"script":"#!/bin/bash \\n hello=$jj1 \\n echo $hello \\n echo $jj1 \\n echo $jj2 \\n for el1 in $jj3 \\n do \\n echo "$el1" \\n done \\n for el2 in $jj4 \\n do \\n echo "$el2" \\n done"}'
j = json.loads(jsonDataaa)
shell_script = j['script']
print "start"
subprocess.call(shell_script, shell=True)
print "end"
下面是我得到的错误 -
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 113 (char 112)
我应该得到这样的预期输出 -
[0, 3, 5, 7, 9]
[1, 2, 4, 6, 8]
start
Hello World 1
Hello World 2
0
3
5
7
9
1
2
4
6
8
end
更新:-
如果我有这样的 jsonDataaa
jsonDataaa = '{"script":"#!/bin/bash \\n hello=$jj1 \\n echo $hello \\n echo $jj1 \\n echo $jj2 \\n"}'
然后它工作正常...而且我能够正确执行它..但是如果我的 jsonDataaa 正如我在问题中提到的那样,那么它只会给我一个错误。我在想可能有一些我无法理解的语法错误。
【问题讨论】: