• 技术文章 >后端开发 >Python教程

    shell可以执行python吗

    anonymityanonymity2019-06-14 11:42:50原创2112
    shell可以执行python吗?

    实际案例:shell调用python脚本,并且向python脚本传递参数

    shell中:

    python test.py $para1 $para2

    python中:

    import sys
    def main($canshu1, $canshu2)
      .....
    main(sys.argv[1], sys.argv[2])

    使用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吗的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:Python
    上一篇:python输出数字要带引号吗 下一篇:python能生成exe程序吗
    千万级数据并发解决方案

    相关文章推荐

    • python shell如何运行• python如何调用api接口• python如何跳出while循环• python中字符串可以遍历吗
    1/1

    PHP中文网