Greed
Greed

Reputation: 73

Running command lines in python

I'm having troubles running commands lines in python. I'm currently using

os.system("cd " + path)
os.system(command)

However, os.system opens a new console each time.

What class should i use for it to work ? How can I intercept the output ?

Thanks !

Upvotes: 1

Views: 294

Answers (3)

null
null

Reputation: 150

I always use os.chdir("dirname") This function can work just like the cd function, so you can do both os.chdir("dir_thats_right_here") and os.chdir("/dir/thats/far/away")

Upvotes: 0

Daniel
Daniel

Reputation: 19547

To fix the above:

os.chdir(path)
os.system(command)

To capture data I would look into subprocess: http://docs.python.org/2/library/subprocess.html

Since you are using python 1.7:

output=os.popen(command,"r").readlines()

Upvotes: 1

Ian Atkin
Ian Atkin

Reputation: 6346

from subprocess import call
call(["ls", "-l"])

The advantage of subprocess versus system is that it is more flexible. You can get the stdout, stderr, the "real" status code, better error handling, etc.

Also, check out the Python docs.

Upvotes: 8

Related Questions