一个计算机技术爱好者与学习者

0%

好好学Shell:Shell和Python互相调用

1. 前言

在linux上,最常用的编程语言是shell,其次是python。而这两种语言,很多时候需要配合使用。本文就研究一下这两种语言互相调用的方法。

参考文档:

2. shell调用python

2.1. 调用python脚本

shell调用python脚本

1
python main.py

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

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#scriptname:test.py

def helloworld():
return "helloworld"

def echo():
print helloworld()

def get_user():
return "haojin",100,"beijing"

2、shell调用python脚本

1
2
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命令

1
2
3
4
import os

val = os.system('ls -al')
print val

其中,val的值是exit code。

3.2. 调用shell脚本

1、准备shell脚本 main.sh

1
2
3
#!/bin/bash

echo "hello"

2、python调用shell脚本

1
2
3
import os
val = os.system('sh main.sh')
print val

3.3. 获取shell指令的结果

例1:获取echo命令结果。

1
2
3
4
5
import os

res = os.popen('echo "hello"')
print res.read()
res.close()

例2:获取curl命令的返回结果,转化成dict。
1、准备shell脚本 main.sh

1
2
3
#!/bin/bash

curl -s "http://rap2api.taobao.org/app/mock/241888/example/1578301745121"

2、python调用shell脚本

1
2
3
4
5
6
7
8
9
import os
import 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

1
2
3
4
#!/bin/bash

echo "hello"
echo $1

2、准备python脚本 main.py

1
2
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
# -*- coding: utf-8 -*-
import http.server
import socketserver
import subprocess
import urllib.parse

# 设置服务器端口
PORT = 8000

# 自定义请求处理程序
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# 检查请求路径是否为指定的API路径
if self.path == "/api/test":
# 执行main.sh脚本
result = subprocess.run(['./main.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# 发送HTTP响应
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:
# 如果路径不匹配,返回404 Not Found
self.send_response(404)
self.end_headers()
self.wfile.write(b"404 Not Found")

def do_POST(self):
# 解析 POST 请求的内容
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)

# 检查请求路径是否为指定的 API 路径
if self.path == "/api/test":
# 获取 POST 参数,例如,假设有一个参数名为 'param'
param_value = parsed_data.get('param', [''])[0]
# 执行main.sh脚本
result = subprocess.run(['./main.sh', param_value], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# 发送HTTP响应
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:
# 如果路径不匹配,返回404 Not Found
self.send_response(404)
self.end_headers()
self.wfile.write(b"404 Not Found")

# 启动HTTP服务器
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()

3、启动web服务

1
python3 main.py

4、调用web服务,web服务调用shell

1
2
curl localhost:8000/api/test
curl -X POST localhost:8000/api/test -d "param=test"
  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-shell-python/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~