python - 不理解 python 中的返回行为

标签 python

我只是尝试一个简单的代码:

import sys

def main():
    print "this is main"
    return "string1"

if __name__ == "__main__":
    sys.exit(main())

当我运行这段代码时,它会给出随机结果,有时“string1”在“this is main”之前,有时在它之后。

为什么会这样?

2 个示例输出:

this is main

string1

Process finished with exit code 1

============

string1

this is main

Process finished with exit code 1

最佳答案

sys.exit 获取 main() 的返回值并将其生成为应用程序的错误代码。该值通常应该是数字,尽管 Python 在这里有点棘手。

来自 sys.exit 的文档:

If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

因此,可能发生的情况是刷新 stdout(用于 print)和输出到 stderr(如上面指定的)之间的竞争。

我建议您尝试在 print (sys.stdout.flush) 之后刷新 stdout 并查看是否可以通过这种方式获得一致的输出.

关于python - 不理解 python 中的返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817307/

相关文章:

python - 使用 2d numpy 数组切片 3d numpy 数组

python - 使用 Seaborn FacetGrid 从数据框中绘制错误条

Python PIL 在渲染文本时添加额外的字符

python - 在 TF 2.1 功能 API 中使用 tf.hub.KerasLayer 会引发 ValueError : Python inputs incompatible with input_signature:

python - selenium.common.exceptions.ElementNotVisibleException : Message: element not interactable using Selenium

python - PyYAML 转储格式

python - 使用 defaultdict 搜索键及其值

python - 我怎样才能用这个结构做到这一点?

python - 祖先的 NDB 查询返回的不是实体

python - 如何比较 python 函数的性能?