0%

Shell和Python互相调用

前言

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

参考文档:

shell调用python

调用python脚本

shell调用python脚本,直接调用即可,例如:

1
python main.py

调用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

调用python函数

1、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中调用 test.py 中的方法

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")

python调用shell

调用shell命令

main.py内容为

1
2
3
4
import os

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

其中,val的值是exit code。

执行main.py,python main.py

调用shell脚本

1、main.sh 内容为

1
2
3
#!/bin/bash

echo "hello"

2、python 调用 main.sh

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

获取shell指令的结果

例子:获取echo命令结果。

1
2
3
4
5
import os

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

高级例子:获取curl命令的返回结果,转化成dict。
1、main.sh 内容为

1
2
3
#!/bin/bash

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

2、python 调用 main.sh

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']
  • 本文作者: 好好学习的郝
  • 本文链接: https://www.voidking.com/dev-shell-python/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!源站会及时更新知识点及修正错误,阅读体验也更好。欢迎分享,欢迎收藏~