【问题标题】:How to extract the output of a cmd query to a textfile using python如何使用 python 将命令提示符输出转换为文本文件 [关闭]
【发布时间】:2021-02-28 11:07:20
【问题描述】:

如何使用 Python 将命令提示符的输出转换为文本文件

import os 
with open ('ip-source.txt') as file:
      test = file.read()
      test = test.splitlines()
      for ip in test:
        os.system('ping -n 20 {}'.format(ip))
#check packet loss in 20s 
#want convert into text file   

  


【问题讨论】:

  • 它无法工作,无法从 cmd 获取输出。但可以处理简单的代码
  • 你可以在简单的代码上做到这一点,但在更大的代码中你应该使用logging模块。

标签: python cmd command-prompt ping python-3.8


【解决方案1】:

我认为最简单的解决方案是将输出转发到文件中。
ping -n 20 {ip_addr} >output.txt
(执行“>>”以追加而不是覆盖)
此外,您应该使用subprocess.Popen() 而不是os.system() 以获得良好的实践。 然后,您可以像往常一样打开文本文件并执行您想要执行的操作。\

编辑
如果您在命令行上执行ls > output.txt,您通常在终端中看到的文本将在“>”运算符之后写入文件。做subprocess.Popen("ping -n 20 {} >> output.txt".format(ip),shell=True) 本质上是一样的。 (我在这种情况下使用>>,不是每次都用最新的输出覆盖文件,而是追加新的内容)

import subprocess 
with open ('ip-source.txt') as file:
      test = file.read()
      test = test.splitlines()
      for ip in test:
          subprocess.Popen('ping -n 20 {} >> ping_output.txt'.format(ip),shell=True)


我希望这是您正在寻找的解决方案,我对您的理解是正确的。
问候,拉斯

【讨论】:

  • 不太明白。你能举一些例子吗?非常感谢!!
  • 您帮我解决了问题,非常感谢!!!
  • 如果是这样,如果您将问题标记为已接受以便其他人也知道,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2011-12-11
  • 2014-09-28
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多