gpt4 book ai didi

Python 不按顺序打印消息

转载 作者:行者123 更新时间:2023-12-04 02:32:54 26 4
gpt4 key购买 nike

如果我有这个代码

def soft_assert(condition):
if not condition:
print('start')
traceback.print_stack()
print('finish')

soft_assert(False)
soft_assert(False)

每次运行输出都不一样:

  File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 38, in <module>
soft_assert(False, 'message 1')
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 30, in soft_assert
traceback.print_stack()
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 41, in <module>
soft_assert(False, 'message 4')
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 30, in soft_assert
traceback.print_stack()
start
finish
start
finish

start
finish
start
finish
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 38, in <module>
soft_assert(False)
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 30, in soft_assert
traceback.print_stack()
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 41, in <module>
soft_assert(False)
File "/Users/spleshakov/Documents/api-testing-with-pytest/tenants/test_uc.py", line 30, in soft_assert
traceback.print_stack()

输出可以是你能想到的任何顺序

这对我来说没有意义,我找不到答案,所以我希望社区可以帮助我解决这些问题:

  1. 为什么会这样?
  2. 如何让等待一个 print 完成,然后再执行另一个?

谢谢

最佳答案

问题是它默认打印到 stderr,而不是 stdout:

# Used by print_stack
def print_list(extracted_list, file=None):
if file is None: # Note here
file = sys.stderr
for item in StackSummary.from_list(extracted_list).format():
print(item, file=file, end="")

你得到乱序的输出,因为这两个流被同时打印到同一个控制台。

指定 file 参数,使其全部打印到同一流:

from sys import stdout

def soft_assert(condition):
if not condition:
print('start')
traceback.print_stack(file=stdout) # Print to stdout
print('finish')

关于Python 不按顺序打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63161548/

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