1. 前言
在linux上,最常用的编程语言是shell,其次是python。而这两种语言,很多时候需要配合使用。本文就研究一下这两种语言互相调用的方法。
参考文档:
2. shell调用python
2.1. 调用python脚本
shell调用python脚本
2.2. 调用python模块
举个简单的例子,我们想要对curl获取的结果进行json格式化。
假设安装了jq,可以使用jq命令:
| 1
 | curl -s "http://rap2api.taobao.org/app/mock/241888/example/1578301745121" | jq
 | 
假设没有安装jq,那我们可以使用python的 json.tool 模块:
| 1
 | curl -s "http://rap2api.taobao.org/app/mock/241888/example/1578301745121" | python -m json.tool
 | 
2.3. 调用python函数
1、准备python脚本 test.py
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | 
 
 
 def helloworld():
 return "helloworld"
 
 def echo():
 print helloworld()
 
 def get_user():
 return "haojin",100,"beijing"
 
 | 
2、shell调用python脚本
| 12
 3
 4
 5
 6
 7
 
 | python -c 'import test;print test.helloworld()'python -c 'import test;test.echo()'
 
 res=$(python -c 'import test;print test.get_user()')
 name=$(echo $res | cut -d' ' -f1 | sed 's/,$//' | sed 's/^(//' | sed "s/\'//g")
 score=$(echo $res | cut -d' ' -f2 | sed 's/,$//')
 loc=$(echo $res | cut -d' ' -f3 | sed 's/)$//' | sed "s/\'//g")
 
 | 
3. python调用shell
3.1. 调用shell命令
python调用shell命令
| 12
 3
 4
 
 | import os
 val = os.system('ls -al')
 print val
 
 | 
其中,val的值是exit code。
3.2. 调用shell脚本
1、准备shell脚本 main.sh
| 12
 3
 
 | #!/bin/bash
 echo "hello"
 
 | 
2、python调用shell脚本
| 12
 3
 
 | import osval = os.system('sh main.sh')
 print val
 
 | 
3.3. 获取shell指令的结果
例1:获取echo命令结果。
| 12
 3
 4
 5
 
 | import os
 res = os.popen('echo "hello"')
 print res.read()
 res.close()
 
 | 
例2:获取curl命令的返回结果,转化成dict。
1、准备shell脚本 main.sh
| 12
 3
 
 | #!/bin/bash
 curl -s "http://rap2api.taobao.org/app/mock/241888/example/1578301745121"
 
 | 
2、python调用shell脚本
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | import osimport json
 
 res = os.popen('sh main.sh')
 data = json.loads(res.read())
 res.close()
 print data['number']
 print data['string']
 print data['array'][0]['foo']
 
 | 
4. python web服务调用shell
1、准备shell脚本 main.sh
| 12
 3
 4
 
 | #!/bin/bash
 echo "hello"
 echo $1
 
 | 
2、准备python脚本 main.py
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 
 | import http.server
 import socketserver
 import subprocess
 import urllib.parse
 
 
 PORT = 8000
 
 
 class MyHandler(http.server.SimpleHTTPRequestHandler):
 def do_GET(self):
 
 if self.path == "/api/test":
 
 result = subprocess.run(['./main.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 
 self.send_response(200)
 self.send_header('Content-type', 'text/html')
 self.end_headers()
 
 
 response_content = f"Script Output: {result.stdout}\nScript Error: {result.stderr}"
 self.wfile.write(response_content.encode())
 else:
 
 self.send_response(404)
 self.end_headers()
 self.wfile.write(b"404 Not Found")
 
 def do_POST(self):
 
 content_length = int(self.headers['Content-Length'])
 post_data = self.rfile.read(content_length).decode('utf-8')
 parsed_data = urllib.parse.parse_qs(post_data)
 
 
 if self.path == "/api/test":
 
 param_value = parsed_data.get('param', [''])[0]
 
 result = subprocess.run(['./main.sh', param_value], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 
 self.send_response(200)
 self.send_header('Content-type', 'text/html')
 self.end_headers()
 
 
 response_content = f"Script Output: {result.stdout}\nScript Error: {result.stderr}"
 self.wfile.write(response_content.encode())
 else:
 
 self.send_response(404)
 self.end_headers()
 self.wfile.write(b"404 Not Found")
 
 
 with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
 print(f"Serving at port {PORT}")
 httpd.serve_forever()
 
 | 
3、启动web服务
4、调用web服务,web服务调用shell
| 12
 
 | curl localhost:8000/api/testcurl -X POST localhost:8000/api/test -d "param=test"
 
 |