如何调用Python的shell脚本函数/变量? [英] How to call a shell script function/variable from python?

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

问题描述

有没有什么办法来调用一个shell脚本,并使用Python的脚本中定义的函数/变量?

该脚本unix_shell.sh

 #!/斌/庆典
函数foo
{
...
}

是否有可能从调用这个蟒蛇函数foo?

解决方案:


  1. 对于函数:壳牌转换功能Python函数

  2. 有关外壳局部变量(非出口),运行中的shell命令,只是打电话python脚本之前:结果
    出口$(集| TR的'\\ n''')


  3. 有关外壳全局变量(从外壳出口),在Python中,您可以:
    进口OS
    打印os.environ [VAR1]



解决方案

没有,这是不可能的。你可以的执行的shell脚本,通过在命令行上的参数,它可以打印出的数据,这可以从Python的解析。

但是,这并不是真正的呼叫的功能。这仍然执行与bash的选择和得到一个字符串返回的标准输入输出。

这可能会做你想要什么。但它可能不这样做的正确方法。巴什不能做很多事情,Python不能。实现的功能在Python来代替。

Is there any way to call a shell script and use the functions/variable defined in the script from python?

The script is unix_shell.sh

#!/bin/bash
function foo
{
...
}

Is it possible to call this function foo from python?

Solution:

  1. For functions: Convert Shell functions to python functions
  2. For shell local variables(non-exported), run this command in shell, just before calling python script:
    export $(set | tr '\n' ' ')

  3. For shell global variables(exported from shell), in python, you can: import os print os.environ["VAR1"]

解决方案

No, that's not possible. You can execute a shell script, pass parameters on the command line, and it could print data out, which you could parse from Python.

But that's not really calling the function. That's still executing bash with options and getting a string back on stdio.

That might do what you want. But it's probably not the right way to do it. Bash can not do that many things that Python can not. Implement the function in Python instead.

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

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