繁体   English   中英

为什么在 python 中我的错误排在第一位,而打印语句排在第二位?

[英]why my errors come first and print statements come second in python?

我编写了一些类,它们是购物车、客户、订单,以及一些用于订单折扣的函数。 这是我的代码的最后几行。

anu = Customer('anu', 4500)  # 1
user_cart = [Lineitem('apple', 7, 7), Lineitem('orange', 5, 6)]  # 2
order1 = Order(anu, user_cart)  # 2
print(type(joe))  # 4
print(order1) # 5

format()  # 6

伙计们,我知道格式会因未传递任何参数而引发错误我问你为什么错误首先出现,如果它首先出现,代码的 rest 如何执行良好。 我认为 python 解释器继续执行代码,当它发现错误时,它会删除所有 output 并抛出该错误。 这是我的 output。

Traceback (most recent call last):
  File "C:\Users\User\PyCharm Community Edition with Anaconda plugin 2019.3.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Users\User\PyCharm Community Edition with Anaconda plugin 2019.3.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "D:/programming/python/progs/my_programs/abc_module/abstract_classes.py", line 97, in <module>
    format()
TypeError: format expected at least 1 argument, got 0
<class '__main__.Customer'>

Congratulations! your order was successfully processed.

Customer name: anu
Fidelity points: 4500 points

Order  :-
    product count: 2
        product        : apple
        amount         : 7 apple(s)
        price per unit : 7$ per 1 apple
        total price    : 49$


        product        : orange
        amount         : 5 orange(s)
        price per unit : 6$ per 1 orange
        total price    : 30$


subtotal        : 79$
promotion       : Fidelity Deal
discount amount : 24.88$
total           : 54.115$

如果我猜对了,您的主要问题是为什么部分代码似乎在检测到错误之前运行? 那是因为 Python 是一种解释语言。

除了在加载文件时检测到的纯语法错误外,在 Python 解释器执行语句时检测到所有错误。

这意味着程序将一直运行,直到其中出现实际错误,因此您拥有的用于初始化和打印的代码将运行,因为其中没有错误。 然后 Python 解释器会检测到format没有任何 arguments 的错误,并报告该错误。


至于为什么先打印错误,然后打印您的程序 output,这是因为错误和正常 output 被写入不同的“文件”。 错误被写入“标准错误”( stderr ),正常 output 被写入“标准输出”( stdout )。

Your IDE catches output to stderr and stdout to different internal buffers, and simply seems to write output to stderr before it writes output to stdout .

发生这种行为是因为出于性能原因,stdout 被缓冲而 stderr 不是。 这意味着当您在标准输出( print指令)上写入内容时可能会有延迟,但在标准错误写入时不会延迟,因此导致标准输出写入发生在标准错误之后。

有关更多详细信息,请参阅内容。

如果您不希望发生这种情况,请使用:

python -u myscript.py

调用脚本时。 这具有禁用标准输出缓冲的效果。

编辑:我看到您在 pycharm 解释器上运行,在这种情况下,您可以通过在run configuration > interpreter options字段中添加-u参数来为 python 解释器使用-u参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM