【问题标题】:How can I save the os commands outputs in a text file? [duplicate]如何将 os 命令输出保存在文本文件中? [复制]
【发布时间】:2019-10-07 00:50:39
【问题描述】:

我正在尝试编写一个使用 os 命令(linux)的脚本并将它们保存在文本文件中。但是当我尝试运行这段代码时,os 命令的输出并没有保存在文本文件中。

#!/usr/bin/python
import sys
import os


target = raw_input('Enter the website : ')
ping_it = os.system('ping ' + target)
string_it = str(ping_it)

with open("Output.txt", "w+") as fo:
        fo.write(string_it)
        fo.close()

在我检查 txt 文件时运行脚本后,我得到的唯一结果是 Output.txt 中的没有 2。

【问题讨论】:

    标签: python file operating-system system


    【解决方案1】:

    欢迎来到 Stackoverflow。

    这里的主要问题是os.system 并非旨在从命令生成输出 - 它只是运行它,然后进程将其输出发送到它从其父级(您的程序)继承的任何内容。

    要捕获输出,最简单的方法是使用subprocess 模块,它允许您捕获进程的输出。

    这是一个相当简单的程序,可以帮助您入门:

    import subprocess
    
    target = 'google.com'
    ping_it = subprocess.Popen('ping ' + target,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    out, err = ping_it.communicate()
    
    with open("Output.txt", "w+") as fo:
            fo.write(str(out))
            fo.close()
    

    如果您想在生成时读取输出而不是等待子进程终止,您可以使用单个 subprocess.PIPE 通道并从中读取,这可以方便地以如下形式表示:

    with Popen(["ping", "google.com"], stdout=PIPE) as proc:
        print(proc.stdout.read())
    

    在此示例中,我选择将命令作为参数列表而不是简单字符串。如果它们已经是列表形式,这避免了必须将它们加入到一个字符串中。

    请注意,当以这种方式与子进程交互时,子进程可能会进入阻塞状态,因为 stdout 或 stderr 已填满其输出缓冲区空间。如果您的程序然后尝试从另一个通道读取,这将创建一个死锁,其中每个进程都在等待另一个进程做某事。为避免这种情况,您可以将 stderr 设为临时文件,然后在子进程完成后验证该文件不包含任何重要内容(理想情况下,将其删除)。

    【讨论】:

      【解决方案2】:

      From docs 您可以使用os.popen 将任何命令的输出分配给变量。

      import os
      target = raw_input('Enter the website : ')
      
      output = os.popen('ping ' + target).read()   # Saving the output
      
      with open('output.txt', 'w+') as f:
          f.write(output)
      

      【讨论】:

      • 请注意,os.popen 及其对等方的此类用途已被弃用很长时间 - 有 notes in the documentation for Python 2 关于如何替换此类过时的用法。
      • 此外,请注意,此答案链接到的文档末尾说 “可用性:Unix、Windows.spawnlp()、spawnlpe()、spawnvp() 和 spawnvpe()在 Windows 上可用。spawnle() 和 spawnve() 在 Windows 上不是线程安全的;我们建议您改用 subprocess 模块。"
      【解决方案3】:

      您究竟想在文件中保存什么?您确实保存了os.command 的输出,这不过是执行的最终状态。这正是文档告诉您该命令的返回值。

      如果您想要ping 命令的输出,您需要使用关注ping 而不是os.command 的内容。简单的方法是添加 UNIX 重定向:

      os.system('ping ' + target + '&> Output.txt')
      

      如果您觉得需要通过 Python 传递结果,请使用单独的进程并接收命令结果; see here.

      您还可以生成一个单独的进程,并在生成结果时逐行检查结果。您似乎不需要,但以防万一,请参阅我自己的问题here

      【讨论】:

        猜你喜欢
        • 2023-03-09
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-27
        • 2013-12-13
        • 1970-01-01
        相关资源
        最近更新 更多