我只是尝试一个简单的代码:
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/