简体   繁体   English

Python程序不会将所有信息都写入.txt,但是会写入外壳

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

Python program won't write all information to .txt but it will to the shell Python程序不会将所有信息都写入.txt,但是会写入外壳

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()

The problems with your code are: 您的代码存在以下问题:

  1. you repeat yourself unecessarily 你不必要地重复自己
  2. except: pass is always wrong except: pass总是错误的
  3. platform.os is not a function type platform.os不是函数类型

The concise and correct version of the code is 简明正确的代码版本是

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("##########")

I make a list of function names in platform that you want to call and then iterate through those names. 我列出了要调用的平台中的函数名称,然后迭代这些名称。 I have removed 'os' from the names because plaftorm.os is just a reference to the module os and I assume that is covered by system 我已经从名称中删除了“ os”,因为plaftorm.os只是对模块os的引用,并且我认为它已被system覆盖

For each name, I generate the label by upcasing it. 对于每个名称,我通过大写来生成标签。 For each name, I get the function with that name from the platform module. 对于每个名称,我从平台模块中获取具有该名称的函数。 To get the return value of calling that function I call it. 要获取调用该函数的返回值,请调用它。 I use the more common way of putting together a formatted string and write it. 我使用更常见的方式将格式化的字符串组合在一起并编写它。 Because the open is wrapped with a context manager, it will close the file for me when the context manager ends. 因为打开文件是用上下文管理器包装的,所以当上下文管理器结束时,它将为我关闭文件。

I catch no exceptions because I don't expect any. 我没有例外,因为我什么也没期待。 If there are any exceptions, there is a bug in my code and I want to know about it as dramatically as possible. 如果有任何例外,我的代码中有一个错误,我想尽可能地了解它。 Uncaught exceptions will ultimately crash the program and print a nice backtrace so I can see where I screwed up. 未捕获的异常最终将使程序崩溃,并打印出不错的回溯记录,这样我就可以知道我在哪里搞砸了。 Silently ignoring exceptions is kinda like duct-taping the mouth and nose of a crying baby, it does quiet things down for the moment only to create a worse problem in the future (dead baby). 默默地忽略例外情况就像是在哭泣的婴儿的嘴巴和鼻子上用胶带扎起来一样,暂时使事情安静下来,只会在将来造成更严重的问题(死去的婴儿)。

Instead of storing the information in tuples, use normal strings. 不要将信息存储在元组中,而应使用普通字符串。 For example: 例如:

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

Even better you can use the format function to have a cleaner code: 更好的是,您可以使用format函数获得更简洁的代码:

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

Also, make sure to catch the exceptions to get an idea of the cause of the problem: 另外,请确保捕获异常以了解问题原因:

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

In addition to the problem that msw stated, I don't understand why you do something like this: 除了msw指出的问题外,我不明白您为什么要执行以下操作:

syslog = log.write(sys)
syslog()

log.write does not return any value (or None value to be precise). log.write不返回任何值( log.writeNone值)。 Yet, you assign that None to a variable and execute that variable as if it is a function. 但是,您可以将None分配给变量,并像执行函数一样执行该变量。

My solution is simpler than that of msw , at the cost of being longer: 我的解决方案比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("##########")

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

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