欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

shell调用python函数_shell调用python函数

发布时间:2025/4/16 python 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 shell调用python函数_shell调用python函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

最近遇到一个需求,需要通过shell调用python中的一个函数,发现其实也挺简单的:

python脚本如下:

test.py:

import ConfigParser

config = ConfigParser.ConfigParser()

config.read("test.conf")

def get_foo():

return config.get("locations", "foo")

def get_bar():

return config.get("locations", "bar")

我想通过shell调用里面的get_foo,只需要在shell中执行一个调用的命令行即可:

python -c 'import test; print test.get_foo()'

-c选项只是告诉python来执行一些python命令。

为了将结果存储在变量中,你可以因此这样做:

RESULT_FOO=`python -c 'import test; print test.get_foo()'`

或者,等效于:

RESULT=$(python -c 'import test; print test.get_foo()')

我们也可以一次调用所有方法,放入一个集合中,再调用切割方法获取相应的值:

ALL_RESULTS=$(python -c 'import test; print test.get_foo(), test.get_bar()')

如果需要第二个结果,并将其放入RESULT_BAR:

RESULT_BAR=$(echo $ALL_RESULTS | cut -d' ' -f2)

总结

以上是生活随笔为你收集整理的shell调用python函数_shell调用python函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。