Python 程序不会将所有信息写入 .txt,但会写入 shell

Python program won't write all information to .txt but it will to the shell

Python 程序不会将所有信息写入 .txt,但会写入 shell

from time import sleep
import platform, os, sys
log = open("reportLog.txt", "w") 
log.write("####REPORT####\n")


try:
    sys =("SYS: " + platform.system()+ ("\n"))
    syslog = log.write(sys)
    syslog()
except:
    pass
try:
    os = ("OS: " + platform.os()+ ("\n"))
    oslog = log.write(os)
    oslog()

except:
    pass
try:
    platform = ("PLATFORM: "+ platform.platform()+ ("\n"))
    platoformlog = log.write(platform)
    platofrmlog()
except:
    pass
try:
    mac_ver("MAC_VER: " + platform.mac_ver()+ ("\n"))
    mac_verlog = log.write(mac_ver)
    mac_verlog()
except:
    pass
try:
    dist =("DIST: " + platform.dist()+ ("\n"))
    distlog = log.write(dist)
    distlog()
except:
    pass
try:
    node = ("NODE: " + platform.node()+ ("\n"))
    nodelog = log.write(node)
    nodelog()
except:
    pass
try:
    arch =("ARCHITECTURE: " + platform.architecture()+ ("\n"))
    archlog = log.write(arch)
    archlog()
except:
    pass
try:
    machine =("MACHINE: " + platform.machine() + ("\n"))
    machinelog = log.write(machine)
    machinelog()
except:
    pass
try:
    cpu =("CPU: " + platform.processor() + ("\n"))
    cpulog = log.write(cpu)
    cpulog()

except:
     pass
log.write("##########")
log.close()

不要将信息存储在元组中,而是使用普通字符串。例如:

sys = "SYS: " + platform.system()+ "\n"
syslog = log.write(sys)

更好的是,您可以使用格式函数来获得更清晰的代码:

sys = "SYS: {0}\n".format(platform.system())
syslog = log.write(sys)

另外,确保捕获异常以了解问题的原因:

try:
    sys = "SYS: " + platform.system()+ "\n"
    syslog = log.write(sys)
except Exception as e:
    print(e)

您的代码存在的问题是:

  1. 你重复自己的话
  2. except: pass总是错的
  3. platform.os不是函数类型

代码的简洁正确版本是

import platform

with open("reportLog.txt", "w") as log:
    log.write("####REPORT####\n")

    names =  """dist system platform mac_ver dist node architecture 
        machine processor""".split()

    for name in names:
        label = name.upper()
        getter = getattr(platform, name)
        value = getter()

        log.write('{}: {}\n'.format(label, value))

    log.write("##########")

我列出了您要调用的平台中的函数名称,然后遍历这些名称。我从名称中删除了 'os',因为 plaftorm.os 只是对模块 os 的引用,我假设它包含在 system

对于每个名字,我通过大写来生成标签。对于每个名称,我从平台模块中获取具有该名称的函数。为了获得调用该函数的 return 值,我调用了它。我使用更常见的方式将格式化字符串放在一起并编写它。因为打开是用上下文管理器包装的,所以当上下文管理器结束时它会为我关闭文件。

我没有发现任何异常,因为我不希望有任何异常。如果有任何异常,则表明我的代码中存在错误,我想尽可能多地了解它。未捕获的异常最终会导致程序崩溃并打印一个漂亮的回溯,这样我就可以看到我搞砸了的地方。默默地忽略异常有点像用胶带封住哭闹婴儿的嘴巴和鼻子,它暂时让事情安静下来只会在未来造成更糟糕的问题(死去的婴儿)。

除了msw说的问题,我不明白你为什么要这样做:

syslog = log.write(sys)
syslog()

log.write 没有 return 任何值(或者 None 值更准确)。然而,您将 None 分配给一个变量并像执行函数一样执行该变量。

我的解决方案比 msw 的解决方案更简单,代价是更长:

with open("reportLog.txt", "w") as log:
    log.write("####REPORT####\n")
    log.write('SYS: {}\n'.format(platform.system()))
    # Other log.write lines here...
    log.write("##########")