【问题标题】:How to pass output of a command in cmd to a txt file using python?如何使用python将cmd中的命令输出传递给txt文件?
【发布时间】:2020-11-19 00:41:43
【问题描述】:

有没有一种方法可以使用 python 将 CMD 命令的输出传递给.txt 文件?

类似这样的:

 import os
 os.system('cmd /c "netsh wlan show profiles"')
 #output=OUTPUT
 output_file=open(outputfile+'.txt','w')
 output_file.write(OUTPUT)
 output_file.close()

有没有办法做到这一点?

【问题讨论】:

    标签: python windows cmd operating-system


    【解决方案1】:
    import subprocess
    out = subprocess.getoutput("ls -l")
    print(out)
    

    现在您可以使用open()file.read() 方法将此输出传递给txt 文件

    【讨论】:

      【解决方案2】:

      您可以将输出传递到临时文件。下面是一个简单的例子:

      import os
      os.system('cmd /c "netsh wlan show profiles" > tmp.txt')
      

      然后您可以只读取 tmp.txt 文件并查看输出。此解决方案基于您的代码。

      还有其他选项,例如使用subprocess,您可以在以下链接中阅读更多内容:https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module

      【讨论】:

        【解决方案3】:

        这里已经有类似的问题了:Running shell command and capturing the output

        import subprocess
        output = subprocess.check_output(["echo", "Hello, World!"])
        

        【讨论】:

          【解决方案4】:

          试试这个库https://docs.python.org/3/library/subprocess.html

          方法subprocess.run() 应该可以完成这项工作。它允许在参数capture_output=True时捕获stdout和stderr

          【讨论】:

            猜你喜欢
            • 2019-03-23
            • 1970-01-01
            • 2012-11-07
            • 1970-01-01
            • 2020-03-28
            • 2014-02-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多