5

I think this is a pretty basic question, but here it is anyway.

I need to write a python script that checks to make sure a process, say notepad.exe, is running. If the process is running, do nothing. If it is not, start it. How would this be done.

I am using Python 2.6 on Windows XP

Hubert Kario
  • 21,314
  • 3
  • 24
  • 44
Zac Brown
  • 5,905
  • 19
  • 59
  • 107

3 Answers3

15

The process creation functions of the os module are apparently deprecated in Python 2.6 and later, with the subprocess module being the module of choice now, so...

if 'notepad.exe' not in subprocess.Popen('tasklist', stdout=subprocess.PIPE).communicate()[0]:
    subprocess.Popen('notepad.exe')

Note that in Python 3, the string being checked will need to be a bytes object, so it'd be

if b'notepad.exe' not in [blah]:
    subprocess.Popen('notepad.exe')

(The name of the file/process to start does not need to be a bytes object.)

JAB
  • 20,783
  • 6
  • 71
  • 80
  • +1, That is an important point. I went with os.process() for the sake of shorter demonstration, but it is important to note that subprocess is far more powerful (and of course not deprecated). – andyortlieb Jul 09 '10 at 18:56
4

There are a couple of options,

1: the more crude but obvious would be to do some text processing against:

os.popen('tasklist').read()

2: A more involved option would be to use pywin32 and research the win32 APIs to figure out what processes are running.

3: WMI (I found this just now), and here is a vbscript example of how to query the machine for processes through WMI.

andyortlieb
  • 2,326
  • 3
  • 21
  • 33
  • Just to offer a bit more clarification, the first option becomes extremely simple with a regex search >>> bool ( re.search('notepad.exe',os.popen('tasklist').read()) ) – andyortlieb Jul 09 '10 at 18:12
  • 1
    You don't even need regex. A simple `if substring in string:`-type statement works just fine. (Or rather, `not in`, since it's supposed to execute when the process isn't active.) – JAB Jul 09 '10 at 18:16
  • This is exactly what I needed! Thansk so much! – Zac Brown Jul 09 '10 at 18:25
  • I did this: import os process = os.popen("tasklist").read() if "notepad" in process: print "Process Running" else: print "Process Terminated" It work perfectly! Thanks again for everyones help! – Zac Brown Jul 09 '10 at 18:26
  • 1
    I would like to point out, you risk a relatively unlikely false positive if another process has the substring "notepad.exe" within its own name, but you'll notice that every process is the the first thing on its line, so it may suffice to search for "\nnotepad.exe", to include that new line. – andyortlieb Jul 09 '10 at 19:05
3

Python library for Linux process management

Community
  • 1
  • 1
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60