Question

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!

Was it helpful?

Solution

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' 

OTHER TIPS

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.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top