1

How can I get a list of running jobs in python. ie. I basically want the output of the jobs command in a string or list or set.

I am currently trying

 p1 = subprocess.Popen(['jobs'], shell=True, stdout=subprocess.PIPE)
 n = p1.communicate()[0].strip()

But this doesnt seem to be working

martineau
  • 119,623
  • 25
  • 170
  • 301
ssb
  • 7,422
  • 10
  • 36
  • 61
  • 1
    In what way is it not working? What output is it giving, vs what output are you getting when you run `jobs` on the command line? – David Robinson Sep 19 '12 at 18:48
  • `subprocess.check_output('jobs', shell=True).split('\n')` would be an shorter version to do what you want. – Hans Then Sep 19 '12 at 18:51
  • 2
    The `jobs` command shows jobs managed by the current shell; why would your Popen subshell be managing any jobs? – Wooble Sep 19 '12 at 18:51
  • 1
    Let me rephrase: ``subprocess.check_output('jobs', shell=True).split('\n')` would be a shorter version to **not** do what you want to do. – Hans Then Sep 19 '12 at 18:55

1 Answers1

6

You have to keep track of it yourself. The shell keeps track of all of its subprocess jobs, but you're not a shell, so you have to do the tracking yourself. jobs is a Bash shell builtin command, not an actual executable which is run. When you do subprocess.Popen(['jobs'], shell=True), you're spawning a new shall and asking it for its jobs, which is of course empty since it's a new shell without any running jobs.

If you can't keep track of your own running jobs, you're going to have a harder time. On Linux, you could parse /proc and look for all processes which have you as a parent. On Windows, you could do something like this using a wrapper such as pywin32 or the ctypes module to access the Win32 API.

Community
  • 1
  • 1
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589