Chirag
Chirag

Reputation: 625

Why os.system is not able to redirect to a file? How to enable that?

I am trying to redirect stdout to a file, Where print statements are being redirected but os.system o/p is not.

From This I have tried using ">" operator but not working for me.

I don't want to use subprocess or popen,

Below is the sample code.

Can any one help?

def ExecCMS_AGT_DB(cmd):
        sys.stdout=open(cmd+'.txt','w')
        print "\ncmd $: "+cmd+" start"
        os.system(cmd+" start")
        print "\ncmd $: "+cmd+" stop"
        os.system(cmd+" stop")
        sys.stdout.close()

def ExecCmd():
        OldStdout=sys.stdout
        ExecCMS_AGT_DB("srocms")
        sys.stdout=OldStdout

#if __name__=="__main__":
        ExecCmd()

Upvotes: 1

Views: 531

Answers (1)

rmunn
rmunn

Reputation: 36708

Why don't you want to use subprocess? It's by far the simplest solution. See https://stackoverflow.com/a/3982683/2314532 for more complete details, but the gist of using subprocess.call() to redirect output boils down to:

f = open("outputFile","wb")
subprocess.call(argsArray,stdout=f)

So your posted code would become:

import subprocess

def ExecCMS_AGT_DB(cmd):
        outfile = open(cmd+'.txt','w')
        print "\ncmd $: "+cmd+" start"
        subprocess.call([cmd, "start"], stdout=outfile)
        print "\ncmd $: "+cmd+" stop"
        subprocess.call([cmd, "stop"], stdout=outfile)
        outfile.close()

def ExecCmd():
        ExecCMS_AGT_DB("srocms")

if __name__=="__main__":
        ExecCmd()

No need to save & restore sys.stdout, and nothing complicated. Just supply the parameter stdout to subprocess.call, and you've solved your problem. Easily, simply, and Pythonically.

Upvotes: 3

Related Questions