2

I am using os.system to submit a command to the system.

I.e.,

import os
os.system(my_cmd)

But I was wondering how could I obtain the output, i.e., let us say i am in the bash and I type in my cmd, I'd get an output of this form:

Job <57960787> is submitted to queue <queueq>.

How can I, in python, using the os.system(cmd), also obtain the text output, and parse it to obtain the job id, 57960787.

Thanks!

Dnaiel
  • 7,622
  • 23
  • 67
  • 126

3 Answers3

6

It is better to use the subprocess module documentation here, example below:

import subprocess,re
p = subprocess.Popen('commands',stdout=subprocess.PIPE,stderr=subprocess.PIPE)
results, errors = p.communicate()
print results
re.search('<(\d+)>', results).group(1) #Cheers, Jon Clements

Or you can even use os.popen documentation here,

p_os = os.popen("commands","r")
line = p_os.readline()
print line
re.search('<(\d+)>', line).group(1) #Cheers, Jon Clements

Or as John Clements kindly suggested, you can use subprocess.check_output, Documentation here

>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n' 
  • First example: `NameError: name 'sub' is not defined` AND `AttributeError: 'str' object has no attribute 'PIPE'`. Please verify for the OP. –  Mar 24 '13 at 20:28
  • 1
    May also want to use the new method in 2.7 if applicable which makes this a bit easier: [subprocess.check_output](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) – Jon Clements Mar 24 '13 at 20:37
  • 1
    @enginefree and you missed the last part of `re.search('<(\d+)>', s).group(1)` to get the job number ;) (where `s` is the output from the command) – Jon Clements Mar 24 '13 at 20:46
1

A simple example:

>>> import os, sys
>>> cmd = "uname"
>>> b = os.popen(cmd, 'r', 1)
>>> b.read()
'Linux\n'

I am running Linux uname command.

os.popen() executes command and return a file type object using that you can read command's output.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
0

os.system does not return output. So instead you can use the commands module.

Example:

import commands
my_cmd = 'ls -l'
status, output = commands.getstatusoutput(my_cmd)
print output
Prabhu S
  • 34
  • 5