【问题标题】:How to store executed command (of cmd) into a variable?如何将执行的命令(cmd)存储到变量中?
【发布时间】:2020-09-10 11:48:39
【问题描述】:

我试过这个:

import os
os.system('tree D://')

但它只是执行我的命令。我无法将其存储到变量中。 我要做的是制作一个可以树本地(如C://)驱动器并搜索指定文件(就像本地搜索引擎)的程序。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

试试(Python3.7+):

import subprocess
data = subprocess.run(["tree", "D://"], capture_output=True)

对于 Python

import subprocess
data = subprocess.run(["tree", "D://"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

【讨论】:

    【解决方案2】:

    你可以试试这个。

    import subprocess
    process = subprocess.Popen(['tree','D://'], stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate()
    

    stdout 应该包含你的命令的输出

    【讨论】:

      【解决方案3】:

      os.system 不是派生或派生新进程的首选方式。对于新流程,请使用 Popen。你可以在这里查看python文档subprocess_2.7_module

      import subprocess
      command = "tree ...whatever"
      p = subprocess.Popen(command, shell=True) #shell=true cos you are running a win shell command
      
      #if you need to communictae with the subprocess use pipes, see below:
      p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      stderrret,stdoutret=p.communicate()
      #now we can parse the output from the child process
      str_command_out = parse_child_output(stdoutret) #we also need to check if child finish without failure!
      do_what_ever_you_like_with(str_command_out)
      

      【讨论】:

      • 我想将 cmd 的响应(在我的命令上)存储到一个变量中。
      • 请参考我在回答中写的链接。你可以用管道做到这一点!通过解析进程(子)输出/标准输出。您可以使用通信的返回元组值来做到这一点: (stdout,stderr)=p.communictae() 希望对您有所帮助。如果您发现它是一个有用的答案,请投票并接受我的答案。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 2012-07-19
      • 2021-11-18
      相关资源
      最近更新 更多