python - 将python脚本的返回值捕获到shell脚本中

标签 python shell

我有一个 shell 脚本,我在其中调用一个 python 脚本说 new.py:

#!/usr/bin/ksh

python new.py

现在这个 new.py 类似于 -

if not os.path.exists('/tmp/filename'):
    print "file does not exist"
    sys.exit(0)

如果文件没有退出,则 python 脚本返回,但 shell 脚本继续执行。如果文件不退出并且我的 python 脚本退出,我希望 shell 脚本也停止在该点。

请建议我如何在 shell 脚本中捕获返回以进一步停止其执行。

最佳答案

您需要从退出函数返回零以外的值。

if os.path.exists("/tmp/filename"):
    sys.exit(0)
else:
    sys.exit(1)

错误值只有 8 位,所以只有整数的低 8 位返回给 shell。如果您提供负数,将返回二进制补码表示的低 8 位,这可能不是您想要的。您通常不会返回负数。

关于python - 将python脚本的返回值捕获到shell脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14850555/

相关文章:

python - 获取 celery AsyncResult 的任务名称

python - 将空字符串值作为日期导入 MySQL

shell - 如何在 Unix 命令行或 shell 脚本中打乱文本文件的行?

python - Windows subprocess.Popen 没有 shell=True 的批处理文件

linux - 在帮助选项中包含子参数以明智地执行?

python - 为什么 random.uniform(0, float ("inf")) 总是返回 inf?

python - MySQLdb、mysqlclient 和 MySQL 连接器/Python 有什么区别?

python - calcOpticalFlowPyrLK 丢失单个跟踪点

node.js - 如何同时为不同项目运行 npm install

java - 从 Java 程序错误执行 Unix Diff