Python:同一程序,运行时打印消息的位置不同

问题描述

如果多次运行相同的脚本,我自己打印的错误消息将随机显示文件的顶部或底部。为什么会改变?

是因为sys.exit()还是因为file = stderr()?

来自书中。我认为作者正在使用file = stderr()为终端中的消息着色。

代码

import sys

ciphertext = """16 12 8 4 0 1 5 9 13 17 18 14 10 6 2 3 7 11 15"""
COLS = 4
ROWS = 5
key = """ -1 2 -3 4 """

def main():
    cipherlist = list(ciphertext.split())
    validate_col_row(cipherlist)


def validate_col_row(cipherlist):
    """Check that input columns and rows are valid vs message length."""
    factors = []
    len_cipher = len(cipherlist)
    for i in range(2,len_cipher):  # range excludes 1-column ciphers
        if len_cipher % i == 0:
            factors.append(i)

    print(f'\nLength of cipher = {len_cipher}')
    print(f'Acceptable column/row values include: {factors}')
    print()

    if ROWS * COLS != len_cipher:
        print('\nError - Input columns and rows not factors of length '
              'of cipher. Terminating program.',file=sys.stderr)
        sys.exit()


main()

所以输出是这样的:

Error - Input columns and rows not factors of length of cipher. Terminating program.

Ciphertext = 16 12 8 4 0 1 5 9 13 17 18 14 10 6 2 3 7 11 15

Trying 4 columns
Trying 5 rows
Trying key =  -1 2 -3 4 

Length of cipher = 19
Acceptable column/row values include: []

或:

Ciphertext = 16 12 8 4 0 1 5 9 13 17 18 14 10 6 2 3 7 11 15

Trying 4 columns
Trying 5 rows
Trying key =  -1 2 -3 4 

Length of cipher = 19
Acceptable column/row values include: []


Error - Input columns and rows not factors of length of cipher. Terminating program.

解决方法

终端中的

stdout是行缓冲的,当stdout是文件时是缓冲的。

stderr流可以使它更快地到达文件,因为它始终是无缓冲的。