Rajodiya Jeel
Rajodiya Jeel

Reputation: 377

How to store executed command (of cmd) into a variable?

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).

Upvotes: 0

Views: 156

Answers (3)

AdamF
AdamF

Reputation: 2950

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)

Upvotes: 1

CanciuCostin
CanciuCostin

Reputation: 1908

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

Upvotes: 1

Gabio
Gabio

Reputation: 9504

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)

Upvotes: 3

Related Questions