472,133 Members | 1,458 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,133 software developers and data experts.

how to get the stdout of the script that os.system executes

5
i know that in python, os.system(cmd) can be used to execute a script or command, and the return value is 0 if successful, rather than the standard output of the script that it executes.

e.g.

>>> a=os.system("echo hello")
>>> a
0 (rather than "hello")

my question is how to direct the standard output into a variable in my python script.
Oct 31 '07 #1
11 44696
The only way I've been able to get output from os.system is to use ">" in the command to make the subshell write its output to a file. Then all I have to do is read the file.
Expand|Select|Wrap|Line Numbers
  1. >>> os.system("echo hello > output.txt")
  2.  
  3. >>> reader = open("output.txt")
  4. >>> print reader.read()
  5. hello 
If you want to just append to the file instead of truncating then appending, use ">>" instead of ">".

It would be nice if there was a more direct method, so hopefully someone else knows one. I'd be very interested to know what it is.
Oct 31 '07 #2
Smygis
126 100+
It would be nice if there was a more direct method, so hopefully someone else knows one. I'd be very interested to know what it is.
Tere is the commands module.

[code=python]
>>> import commands
>>> print commands.getoutput("echo helllo")
helllo
>>> import commands
>>> print commands.getoutput("echo hello")
hello
>>> txt = commands.getoutput("uname -a")
>>> print txt
Linux Bob 2.6.20-15-server #2 SMP Sun Apr 15 07:41:34 UTC 2007 i686 GNU/Linux
[code]

I also think os.popen works. but i have no experience with that. commands is quick and easy. i think os.popen is more advanced
Oct 31 '07 #3
bartonc
6,596 Expert 4TB
i know that in python, os.system(cmd) can be used to execute a script or command, and the return value is 0 if successful, rather than the standard output of the script that it executes.

e.g.

>>> a=os.system("echo hello")
>>> a
0 (rather than "hello")

my question is how to direct the standard output into a variable in my python script.
Since you have not stated your OS, our freind Smygis has given a great solution (if you are running under *nix). I'd recommend, however, that you use the newer subprocess module.
6.8 subprocess -- Subprocess management

New in version 2.4.

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:


os.system
os.spawn*
os.popen*
popen2.*
commands.*
Oct 31 '07 #4
bartonc
6,596 Expert 4TB
Since you have not stated your OS, our freind Smygis has given a great solution (if you are running under *nix). I'd recommend, however, that you use the newer subprocess module.
Try:
Expand|Select|Wrap|Line Numbers
  1. import subprocess as sub
  2. retcode = sub.call(["ls", "-l"])
And let us know how that works out for you.
Oct 31 '07 #5
bartonc
6,596 Expert 4TB
Try:
Expand|Select|Wrap|Line Numbers
  1. import subprocess as sub
  2. retcode = sub.call(["ls", "-l"])
And let us know how that works out for you.
On Windows, this:
Expand|Select|Wrap|Line Numbers
  1. >>> import subprocess as sub
  2. >>> sub.call(['dir'], shell=True)
worked in a Python command-line shell, but not in my IDE (Boa Constructor).
Oct 31 '07 #6
Smygis
126 100+
Try:
Expand|Select|Wrap|Line Numbers
  1. import subprocess as sub
  2. retcode = sub.call(["ls", "-l"])
And let us know how that works out for you.
Still, that prints the result. And does not return it.

So no, Ill stick with commands.

Whenever i need something like this. And thats only happend like two times.
Oct 31 '07 #7
wxy212
5
Thanks for all of your replies.

"var = commands.getoutput(cmd)" seems to be good. However, it doesn't check if the command has been executed successfully.

What i want is if it's executed successfully, then write the stdout to a variable, otherwise die with an error message..

If i use "if os.system(cmd) != 0:" to check it before running "var=commands.getoutput(cmd)", then the stdout will not only be written to variable var, but also pop on the prompt screen, which is not what I like..

Does anyone have some idea?
Oct 31 '07 #8
Smygis
126 100+
Thanks for all of your replies.

"var = commands.getoutput(cmd)" seems to be good. However, it doesn't check if the command has been executed successfully.

What i want is if it's executed successfully, then write the stdout to a variable, otherwise die with an error message..

If i use "if os.system(cmd) != 0:" to check it before running "var=commands.getoutput(cmd)", then the stdout will not only be written to variable var, but also pop on the prompt screen, which is not what I like..

Does anyone have some idea?
commands.getstatusoutput

Expand|Select|Wrap|Line Numbers
  1. >>> fail = commands.getstatusoutput("ps -q")
  2. >>> notfail = commands.getstatusoutput("ps -A")
  3. >>> fail[0]
  4. 256
  5. >>> len(fail[1]) # the output
  6. 1517
  7. >>> notfail[0]
  8.  
  9. >>> len(notfail[1]) # the output
  10. 3408
  11.  
  12.  
Oct 31 '07 #9
wxy212
5
commands.getstatusoutput

Expand|Select|Wrap|Line Numbers
  1. >>> fail = commands.getstatusoutput("ps -q")
  2. >>> notfail = commands.getstatusoutput("ps -A")
  3. >>> fail[0]
  4. 256
  5. >>> len(fail[1]) # the output
  6. 1517
  7. >>> notfail[0]
  8.  
  9. >>> len(notfail[1]) # the output
  10. 3408
  11.  
  12.  


brilliant!! thanks a lot..
Oct 31 '07 #10
ghostdog74
511 Expert 256MB
note also that commands modules is Unix specific.( AFAIK , correct me if i am wrong)
i use this sometimes
Expand|Select|Wrap|Line Numbers
  1. import os
  2. fin, fout = os.popen4(cmd)
  3. print fout.read() #standard out
  4.  
Nov 2 '07 #11
Smygis
126 100+
note also that commands modules is Unix specific.( AFAIK , correct me if i am wrong)
i use this sometimes
Expand|Select|Wrap|Line Numbers
  1. import os
  2. fin, fout = os.popen4(cmd)
  3. print fout.read() #standard out
  4.  

commands is a simple unix specific wrapper for os.popen:
The whole content of commands.py:

Expand|Select|Wrap|Line Numbers
  1. smygis@Bob:~$ cat /usr/lib/python2.5/commands.py
  2. """Execute shell commands via os.popen() and return status, output.
  3.  
  4. Interface summary:
  5.  
  6.        import commands
  7.  
  8.        outtext = commands.getoutput(cmd)
  9.        (exitstatus, outtext) = commands.getstatusoutput(cmd)
  10.        outtext = commands.getstatus(file)  # returns output of "ls -ld file"
  11.  
  12. A trailing newline is removed from the output string.
  13.  
  14. Encapsulates the basic operation:
  15.  
  16.       pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  17.       text = pipe.read()
  18.       sts = pipe.close()
  19.  
  20.  [Note:  it would be nice to add functions to interpret the exit status.]
  21. """
  22.  
  23. __all__ = ["getstatusoutput","getoutput","getstatus"]
  24.  
  25. # Module 'commands'
  26. #
  27. # Various tools for executing commands and looking at their output and status.
  28. #
  29. # NB This only works (and is only relevant) for UNIX.
  30.  
  31.  
  32. # Get 'ls -l' status for an object into a string
  33. #
  34. def getstatus(file):
  35.     """Return output of "ls -ld <file>" in a string."""
  36.     return getoutput('ls -ld' + mkarg(file))
  37.  
  38.  
  39. # Get the output from a shell command into a string.
  40. # The exit status is ignored; a trailing newline is stripped.
  41. # Assume the command will work with '{ ... ; } 2>&1' around it..
  42. #
  43. def getoutput(cmd):
  44.     """Return output (stdout or stderr) of executing cmd in a shell."""
  45.     return getstatusoutput(cmd)[1]
  46.  
  47.  
  48. # Ditto but preserving the exit status.
  49. # Returns a pair (sts, output)
  50. #
  51. def getstatusoutput(cmd):
  52.     """Return (status, output) of executing cmd in a shell."""
  53.     import os
  54.     pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  55.     text = pipe.read()
  56.     sts = pipe.close()
  57.     if sts is None: sts = 0
  58.     if text[-1:] == '\n': text = text[:-1]
  59.     return sts, text
  60.  
  61.  
  62. # Make command argument from directory and pathname (prefix space, add quotes).
  63. #
  64. def mk2arg(head, x):
  65.     import os
  66.     return mkarg(os.path.join(head, x))
  67.  
  68.  
  69. # Make a shell command argument from a string.
  70. # Return a string beginning with a space followed by a shell-quoted
  71. # version of the argument.
  72. # Two strategies: enclose in single quotes if it contains none;
  73. # otherwise, enclose in double quotes and prefix quotable characters
  74. # with backslash.
  75. #
  76. def mkarg(x):
  77.     if '\'' not in x:
  78.         return ' \'' + x + '\''
  79.     s = ' "'
  80.     for c in x:
  81.         if c in '\\$"`':
  82.             s = s + '\\'
  83.         s = s + c
  84.     s = s + '"'
  85.     return s
  86.  
Nov 2 '07 #12

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by Sticks | last post: by
4 posts views Thread by Paul Nilsson | last post: by
5 posts views Thread by alexLIGO | last post: by
1 post views Thread by Russ | last post: by
6 posts views Thread by tatamata | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.