方案一(查看很多博客,用这种方法,感觉是靠谱的,可自己运行报错SyntaxError: invalid syntax
,这个应该是导入未生效,所有调用python里方法就报错了,用不了,不知道是否和我python版本有关系,python3.6)shell脚本调用如下:
res=`python -c 'import test; print test.get_test_list(${param_name})'`
echo $res
方案二(由于上一种方法,报错,只有选择这种方案,虽然并不是很完美,python文件中print的内容都能输出,但勉强能用,把多余的print去掉了,只留了自己想要的输出)shell脚本调用如下:
res=$(python3 ${BASE_DIR}/test.py ${param_name} 2>&1)
echo "res: $res"
shell脚本调用python代码示例,执行shell脚本时:./test.sh params_name
test.sh代码示例
#!/bin/bash
echo "${BASH_SOURCE[0]}"
# /home/dev/work
RUN_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
res=$(python3 ${RUN_DIR}/test.py -arg ${param_name} 2>&1)
echo "res: $res"
# ['t1', 't1_0', 't1_1', 't1_2', 't1_3', 't1_4', 't1_5', 't1_6', 't1_7']
ary=(${res//,/ })
count=${#ary[*]}
echo "count: $count"
# 8
python代码示例,请注意了,main函数接收调用参数的,python的main函数接收调用参数:param_1 = sys.argv[1],main函数执行代码逻辑的!
test.py代码示例:
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import sys
import json
import requests
import ast
def get_test_list(param_name):
url_test = 'http://localhost:8080/data.demo/querydata'
json_object = {
'param_name': param_name
}
#print(json_object)
head = {'Content-Type': 'application/json'}
res = requests.post(url=url_test, json=json_object, headers=head).text
#print(res)
res_json = json.loads(res)
#print(res_json)
code = res_json['code']
if code == '200':
param_test = ast.literal_eval(res_json['data'][0]['test'])
# print(param_test)
else:
param_test = None
return param_test
if __name__ == '__main__':
#获取调用python脚本时的参数:sys.argv[1]
param_1 = sys.argv[1]
res = get_test_list(param_1)
print(res)