如何从Python脚本返回一个值作为Bash变量? [英] How to return a value from Python script as a Bash variable?

查看:69
本文介绍了如何从Python脚本返回一个值作为Bash变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的摘要:

# import whatever

def createFolder():
    #someCode
    var1=Gdrive.createFolder(name)
    return var1 

def main():
    #someCode
    var2=createFolder()
    return var2

if __name__ == "__main__":
    print main()

我设法向bash变量返回值的一种方法是打印从 main()返回的内容.另一种方法是在脚本的任何位置打印变量.

One way in which I managed to return a value to a bash variable was printing what was returned from main(). Another way is just printing the variable in any place of the script.

有没有办法以更 pythonic 的方式返回它?

Is there any way to return it in a more pythonic way?

该脚本的调用方式为:

folder=$(python create_folder.py "string_as_arg")

推荐答案

如果您正在bash中工作,则可以简单地做到:

If you were working in bash then you could simply do:

export var="value"

但是,Python中没有这样的等效项.如果尝试使用os.environ,则这些值将在其余过程中保持不变,并且在程序完成后将不会进行任何修改.最好的选择是完全按照自己的意愿做.

However, there is no such equivalent in Python. If you try to use os.environ those values will persist for the rest of the process and will not modify anything after the program finishes. Your best bet is to do exactly what you are already doing.

这篇关于如何从Python脚本返回一个值作为Bash变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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