0

I want the output of the jobs command run in the shell as a string in python.

I have this code

import subprocess p1 = subprocess.Popen(['jobs'], shell=True, stdout=subprocess.PIPE) print p1.communicate() 

But this doesnt seem to work. The output I get is -

('', None) 

How do I fix this?

4
  • 2
    Which Python version and OS are you on? It works fine on Linux, Python 2.5.2. Commented Sep 19, 2012 at 9:58
  • 1
    What is the value of p1.returncode? (Btw., you don't need shell=True.) Commented Sep 19, 2012 at 9:58
  • 1
    I believe you are testing different code (the print statement as shown will output a string, not a tuple). Maybe there are other differences besides the print statement, which cause trouble. The code as shown works for me (Linux, Python 2.7.3). Commented Sep 19, 2012 at 10:03
  • i copied out the wrong block of code :P.... changed it now though! Commented Sep 19, 2012 at 13:08

1 Answer 1

1

You can use subprocess.check_output:

In [5]: import subprocess In [6]: output = subprocess.check_output("ps") In [7]: print output PID TTY TIME CMD 2314 pts/2 00:00:06 bash 4084 pts/2 00:00:03 mpdas 7315 pts/2 00:00:02 python 7399 pts/2 00:00:00 ps In [8]: 

Your code works fine for me.

In [11]: import subprocess In [12]: p1 = subprocess.Popen(['ps'], stdout=subprocess.PIPE) In [13]: print p1.communicate()[0] PID TTY TIME CMD 2314 pts/2 00:00:06 bash 4084 pts/2 00:00:03 mpdas 7315 pts/2 00:00:02 python 7682 pts/2 00:00:00 ps In [14]: 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.