1

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 !

3
  • Which OS? Which version of Python? Commented Jan 4, 2013 at 23:49
  • There was no 1.7. I remember the 1.6->2.0 conversion like it was just yesterday and the entire dotcom economy was collapsing and I had lots of time to sit around at home reading PEPs. Maybe you mean 2.7? Commented Jan 5, 2013 at 0:14
  • Sorry I can't edit... Typo it's the 2.7 Commented Jan 5, 2013 at 1:27

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

call(["cd", "C:\Users\Greed"], shell=True) with call(["C:\WINDOWS\Microsoft.NET\Framework\\v3.5\csc.exe", "/optimize", "/out:Main.exe", "C:\Users\Greed\Documents\Visual Studio 2010\Projects\Ref\Ref\Program.cs"]) seems to not work ?
@Greed: Each call with shell=True is running in its own shell. Doing a cd there is just going to change that shell's current directory; it won't affect the next one. If you want to actually change the current directory for the Python script, and everything else it launches, use os.chdir instead. Then the call should work. (If not, explain what it does wrong instead of just saying it "seems to not work".)
@IanAtkin: It's not even an old version, it's a version that never existed, or was even contemplated. So clearly, the OP is from a different universe. Possibly one where Guido has no beard!
Wow, you're right. I Google'd it and didn't notice I was looking at Python Paste 1.7.5. BTW: Guido's beard is a fake that he only uses at Py Conventions.
@IanAtkin: Hmmm… I just read that on the internet, so it must be true. Which means in the OP's universe, Guido has a real beard that he only covers up at Py Conventions?
|
1

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

1 Comment

There is no python 1.7. And before 2.0, os.popen was broken on Windows.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.