Python不按顺序打印消息



如果我有这个代码

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')

相关内容

  • 没有找到相关文章

最新更新