关闭文件上的I/O操作;写入fi后尝试在屏幕上打印

2024-05-29 10:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

如果用户选择该选项,我将尝试将屏幕内容写入文本文件。然而,Python似乎想要将"Report Complete."打印到report.txt文件中,我告诉它关闭该文件。我希望“ReportComplete”在写入文本文件后显示在屏幕上,然后转到哈希函数

import wmi
import sys
import hashlib

c = wmi.WMI()
USB = "Select * From Win32_USBControllerDevice"

print ("USB Controller Devices:")
for item in c.query(USB):
    print (item.Dependent.Caption)

print (" ")
print ("======================================")
report = input ("Would you like the results exported to a file? ")

if (report) == "yes":
    file = open('report.txt', 'w')
    sys.stdout = file
    for item in c.query(USB):
        print (item.Dependent.Caption)
    file.close()
    print ("Report complete.")

else:
    print ("Job Complete.")

hashInput = input ("Would you like to hash the report? ")
if (hashInput) == "yes":
    hash = hashlib.md5(open('report.txt', 'rb').read()).hexdigest()
    print ("The MD5 hash value is:", (hash))

else:
    print ("Job Complete.")

Tags: 文件importreporttxt屏幕syshashitem
1条回答
网友
1楼 · 发布于 2024-05-29 10:18:13

sys.stdout设置为文件,然后关闭该文件。这使得您尝试打印的所有内容(通常会转到标准输出)都尝试转到一个关闭的文件。如果我可以建议的话,不要重新分配sys.stdout。这是没有必要的

if report == "yes":
    with open('report.txt', 'w') as fout:
        for item in c.query(USB):
            print(item.Dependent.Caption, file=fout)
    print("Report complete.")

相关问题 更多 >

    热门问题