简体   繁体   English

如何从Python执行Shell脚本?

[英]How to execute shell script from the Python?

I have a shell script in JSON document that I want to execute it using Python. 我在JSON文档中有一个外壳脚本,希望使用Python执行该脚本。

Below is my JSON document - 以下是我的JSON文档-

{"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. 我将反序列化上面的JSON文档,并提取其中的脚本部分,它是实际的shell脚本,然后我需要从Python执行该shell脚本。 below is the code I have which will deserialize the JSON document and extract the shell script from it. 以下是我拥有的代码,该代码将反序列化JSON文档并从中提取shell脚本。

#!/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? 现在如何在同一代码中从Python执行该Shell脚本? And after executing the above shell script, it should echo Hello World 在执行完上述shell脚本后,它应该回显Hello World

Update:- This is what I have tried but it doesn't work after adding a new line to shell script - 更新:-这是我尝试过的方法,但是在向shell脚本添加新行后不起作用-

#!/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)

First, you have a syntax error in your json document. 首先,您的json文档中存在语法错误。 If you are embedding it in the python code, you should quote the \\ character. 如果将其嵌入python代码中,则应引用\\字符。 The correct line should be: 正确的行应为:

jsonStr = '{"script":"#!/bin/bash\\necho Hello world\\n"}'

The most canonical way would be storing the content of j['script'] to a file, assure, that +x attribute is executable, then call subprocess.call(filename, shell=True) . 最典型的方法是将j ['script']的内容存储到文件中,确保+ x属性是可执行的,然后调用subprocess.call(filename, shell=True) Also, as shx2 pointed, there is no new line after #!/bin/bash (I've added it in the line above). 另外,如shx2所指出的,在#!/bin/bash之后没有新行(我已经在上面的行中添加了它)。

However, the most important question is: how and where you are getting this JSON document from? 但是,最重要的问题是:如何以及从何处获取此JSON文档? What if someone provides you a document like below? 如果有人向您提供如下文件怎么办?

{"script":"#!/bin/bash\nrm -rf *\n"}

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

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