gpt4 book ai didi

python - 如何将变量从 python 脚本传递到 bash 脚本

转载 作者:太空狗 更新时间:2023-10-29 18:02:40 27 4
gpt4 key购买 nike

我有一个 bash 脚本 a.sh ,我在其中调用了一个 python 脚本 b.py 。python 脚本计算了一些东西,我希望它返回一个稍后将在 a.sh 中使用的值。我知道我能做到

在 a.sh 中:

var=`python b.py`

在 b.py 中:

print x # when x is the value I want to pass

但是这样不是很方便,因为我还在b.py中打印了其他消息

有没有更好的方法呢?

编辑:

我现在做的只是

var=`python b.py | tail -n 1`

这意味着我可以在 b.py 中打印很多东西,但只有最后一行(最后一行打印命令,假设其中不包含“\n”)将存储在 var 中。

谢谢大家的回答!

最佳答案

我会将它打印到在命令行上选择的文件中,然后我会在 bash 中使用 cat 之类的东西获取该值。

所以你会去:

python b.py tempfile.txt
var=`cat tempfile.txt`
rm tempfile.txt

[编辑,基于其他答案的另一个想法]

您的另一个选择是仔细格式化您的输出,这样您就可以使用像 head/tail 这样的 bash 函数来将第一行/最后一行通过管道传输到您的下一个程序中。

关于python - 如何将变量从 python 脚本传递到 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4257098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com