从调用一个shell脚本,一个Python函数 [英] Calling a Python function from a shell script

查看:370
本文介绍了从调用一个shell脚本,一个Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何从shell脚本调用Python函数。

I am trying to figure out how to call a Python function from a shell script.

我有多种功能Python文件,我需要使用它们返回的值在我的shell脚本。有没有办法做到这一点。

I have a Python file with multiple functions and I need to use the values returned by them in my shell script. Is there a way to do it.

我才能读取使用Python和壳得到的值的配置文件这样做。是否有任何其他更好的方式来实现这一目标。

I am doing this in order to read a config file using Python and getting the values in shell. Is there any other better way to achieve this.

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

我需要由Python函数返回的值存储在一个shell变量。

I need to store the values returned by the Python functions in a shell variable.

推荐答案

您可以通过询问Python的跨preTER打印结果发送你的函数到标准输出结果:

You can send the result of your functions to the standard output by asking the Python interpreter to print the result:

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

-c 选项就是要求Python来执行一些Python命令。

The -c option simply asks Python to execute some Python commands.

为了将结果存储在一个变量,你可以做的,因此:

In order to store the result in a variable, you can therefore do:

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

或等价

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

由于反引号和 $(...)评价一个命令和它的输出代替它。

since backticks and $(…) evaluate a command and replace it by its output.

PS :让每一个函数的结果,需要分析每一次的配置文件,使用这种方法。这可以通过返回所有的结果一气呵成,喜欢的东西进行优化:

PS: Getting the result of each function requires parsing the configuration file each time, with this approach. This can be optimized by returning all the results in one go, with something like:

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

结果可以被分割并放到不同的变量与

The results can then be split and put in different variables with

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

它接受的第二的结果,并把它放在 RESULT_BAR 为例(以及类似: -fn 的结果#N)。

which takes the second result and puts it in RESULT_BAR for example (and similarly: -fn for result #n).

PPS :作为巴勃罗·毛林所提到的,它很可能是更容易做到在单一间preTER一切(Python的,但也许也壳),如果可能的话,而不是计算变量在一个程序中,并用它们在另一个

PPS: As Pablo Maurin mentioned, it would probably be easier to do everything in a single interpreter (Python, but maybe also the shell), if possible, instead of calculating variables in one program and using them in another one.

这篇关于从调用一个shell脚本,一个Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆