0

I have tried this:

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

but it just executes my command. I can't store it into a variable. What I'm going to do is to make a program that can tree a local (like C://) drive and search for specified file (it's like a local search engine).

Gabio
  • 9,126
  • 3
  • 12
  • 32
Rajodiya Jeel
  • 319
  • 4
  • 11
  • Does this answer your question? [How to use subprocess popen Python](https://stackoverflow.com/questions/12605498/how-to-use-subprocess-popen-python) – sushanth May 23 '20 at 16:40
  • Does this answer your question? [Assign output of os.system to a variable and prevent it from being displayed on the screen](https://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on) – Jaap Joris Vens May 23 '20 at 20:32

3 Answers3

3

Try (for Python3.7+):

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

For Python<3.7:

import subprocess
data = subprocess.run(["tree", "D://"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Gabio
  • 9,126
  • 3
  • 12
  • 32
1

You can try this.

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

stdout should contain your command's output

CanciuCostin
  • 1,773
  • 1
  • 10
  • 25
1

os.system is not the prefered way to fork or spawn a new process. for new process use the Popen. u can take a look at the python documentation here 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)
Adam
  • 2,820
  • 1
  • 13
  • 33
  • i want to store the response of cmd (on my command) into a variabe. – Rajodiya Jeel May 23 '20 at 17:13
  • please refer to the link i have wrote in my answer. you can do it with pipes! by parsing the process (child) output/stdoutput. you can do it with the return tuple value of communicate: (stdout,stderr)=p.communictae() hope that helps you further. please vote up and accept my answer if you have found it a useful answer. thanks. – Adam May 23 '20 at 17:16