【发布时间】:2020-09-10 11:48:39
【问题描述】:
我试过这个:
import os
os.system('tree D://')
但它只是执行我的命令。我无法将其存储到变量中。 我要做的是制作一个可以树本地(如C://)驱动器并搜索指定文件(就像本地搜索引擎)的程序。
【问题讨论】:
-
这能回答你的问题吗? How to use subprocess popen Python
标签: python python-3.x
我试过这个:
import os
os.system('tree D://')
但它只是执行我的命令。我无法将其存储到变量中。 我要做的是制作一个可以树本地(如C://)驱动器并搜索指定文件(就像本地搜索引擎)的程序。
【问题讨论】:
标签: python python-3.x
试试(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)
【讨论】:
你可以试试这个。
import subprocess
process = subprocess.Popen(['tree','D://'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
stdout 应该包含你的命令的输出
【讨论】:
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)
【讨论】: