为什么Python中的错误信息在print方法之前显示



我在SO中访问了之前问过的类似问题。在答案中提到:

当缓冲区"flushed"时,将显示该缓冲区。通常情况下,如果输出为终端,缓冲区在新行刷新。

在下面的代码中,我在print语句中设置了flushTrue,但error消息仍然较早显示。

下面是一个在mongoDB数据库中执行CRUD操作的简单程序。

代码:

import pymongo
client = pymongo.MongoClient("mongodb://127.0.0.1/27017")
mydb = client["Employee"]
collection = mydb.collection
# record = {"firstname":"Udesh", "lastname":"Ranjan"}
# collection.insert_one(record)
records = [{"Name":"Your Name", "age":78, "Passion":"Astronomy"},
{"Name":"Your Name", "age":38, "Passion":"Basket Ball"}]
# collection.insert_many(records)
print(collection.find_one(), flush=True) // flushing the output stream
print(dir(collection), flush=True)
# print(collection.find())
condition = {}
# condition = {"age":{"$in":[35, 35, 78, 22]}}
# condition = {"age":{"$lt":100, "$gt":30}}
# condition = {"age":{"$lt":100, "$gt":10}, "Name":"Your Name"}
condition = {"$or":[{"Name":"Your Name"}, {"firstname":"Udesh"}]}
for data in collection.find(condition):
# print(data, type(data))
for index, (key, item) in enumerate(data.items()):
if index != 0:
print(key, item, flush=True)
print()

inventory = mydb.inventory
records = [
{"item":"journal", "qty":30, "size":{"h":14, "w":20, "uom":"cm"}, "price":450.00},
{"item":"journal", "qty":20, "size":{"h":14, "w":25, "uom":"cm"}, "price":350.00},
{"item":"journal", "qty":10, "size":{"h":14, "w":10, "uom":"cm"}, "price":550.00},
{"item":"journal", "qty":3, "size": {"h":14, "w":30, "uom":"cm"}, "price":250.00},
{"item":"journal", "qty":50, "size":{"h":14, "w":50, "uom":"cm"}, "price":150.00},
{"item":"journal", "qty":39, "size":{"h":0.4, "w":.30, "uom":"m"}, "price":5000.00},
{"item":"journal", "qty":25, "size":{"h":140, "w":100, "uom":"mm"}, "price":1453.00},
]
records = []
inventory.insert_many(records)
condition = {}
for record in inventory.find(condition):
print(record)
输出:

C:ProgramDataAnaconda3envstf_gpupython.exe C:UsersdevpaPycharmProjectsMondoDBKrishNaiksrchello.py 
Traceback (most recent call last):
File "C:UsersdevpaPycharmProjectsMondoDBKrishNaiksrchello.py", line 47, in <module>
inventory.insert_many(records)
File "C:UsersdevpaAppDataRoamingPythonPython39site-packagespymongo_csot.py", line 105, in csot_wrapper
return func(self, *args, **kwargs)
File "C:UsersdevpaAppDataRoamingPythonPython39site-packagespymongocollection.py", line 698, in insert_many
raise TypeError("documents must be a non-empty list")
TypeError: documents must be a non-empty list
{'_id': ObjectId('63ad6d71597ce7bc64ed82e0'), 'firstname': 'Udesh', 'lastname': 'Ranjan'}
['_BaseObject__codec_options', '_BaseObject__read_concern', '_BaseObject__read_preference', '_BaseObject__write_concern', '_Collection__create', '_Collection__create_indexes', '_Collection__database', '_Collection__find_and_modify', '_Collection__full_name', '_Collection__name', '_Collection__write_response_codec_options', '__bool__', '__call__', '__class__', '__class_getitem__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__orig_bases__', '__parameters__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_aggregate', '_aggregate_one_result', '_command', '_count_cmd', '_delete', '_delete_retryable', '_insert_one', '_is_protocol', '_read_preference_for', '_retryable_non_cursor_read', '_socket_for_reads', '_socket_for_writes', '_timeout', '_update', '_update_retryable', '_write_concern_for', '_write_concern_for_cmd', 'aggregate', 'aggregate_raw_batches', 'bulk_write', 'codec_options', 'count_documents', 'create_index', 'create_indexes', 'database', 'delete_many', 'delete_one', 'distinct', 'drop', 'drop_index', 'drop_indexes', 'estimated_document_count', 'find', 'find_one', 'find_one_and_delete', 'find_one_and_replace', 'find_one_and_update', 'find_raw_batches', 'full_name', 'index_information', 'insert_many', 'insert_one', 'list_indexes', 'name', 'next', 'options', 'read_concern', 'read_preference', 'rename', 'replace_one', 'update_many', 'update_one', 'watch', 'with_options', 'write_concern']
firstname Udesh
lastname Ranjan
firstname Udesh
lastname Ranjan
Name Your Name
age 78
Passion Astronomy
Name Your Name
age 38
Passion Basket Ball

Process finished with exit code 1

记录为空,返回错误提示。

但是为什么error消息显示在print语句之前,甚至在flushingoutput stream之后呢?

因为您使用显式空的records调用inventory.insert_many。这里有

records = []
inventory.insert_many(records)

删除

records = []

,然后inventory.insert_many(records)行不会告诉你错误。

最新更新