Monitor Process in Python? - python

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

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.)

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.

Python library for Linux process management

Related

How to run a python program from c++

I am trying to make a program in c++, but i cant make the program because in one part of the code I need to run a python program from c++ and I dont know how to do it. I've been trying many ways of doing it but none of them worked. So the code should look sometihnglike this:somethingtoruntheprogram("pytestx.py"); or something close to that. Id prefer doing it without python.h. I just need to execute this program, I need to run the program because I have redirected output and input from the python program with sys.stdout and sys.stdin to text files and then I need to take data from those text files and compare them. I am using windows.
You have two way of doing that:
Use system/fork and exec*/...
Embed a python interpreter in your program (cf python 2.6 doc or boost.python)
Using a embedded interpreter is (IMHO) the best way to do it because it gives you more control over the execution of the script, because it's not OS-dependant and it does not rely on your target having a python interpreter (configured as you require).
There's POSIX popen and on Windows _popen, which is halfway between exec and system. It offers the required control over stdin and stdout, which system does not. But on the other hand, it's not as complicated as the exec family of functions.

terminating application through python script

How to close (terminate) Windows applications using Python script? When I switch-on my PC, I find many applications like MSOSYNC.exe, ONENOTEM.exe etc. along with many others, running, which are not very useful. I want to close those? I tried "subprocess" module and some other, they not working. Which method should I use?
You're using the Popen class to construct a new object in you example already. It has methods to deal with it. Read the documentation
import subprocess
proc = subprocess.Popen(['c:\\windows\\system32\\notepad.exe','C:\\file1.txt'])
proc.terminate()

Python multiprocessing not working when used from C++ [duplicate]

This question already has an answer here:
Embedded python: multiprocessing not working
(1 answer)
Closed 8 years ago.
I'm trying to embed Python 3.3 x64 script with 'multiprocessing' to C++ code under Windows 7 x64.
Simple script like:
from multiprocessing import Process
def spawnWork(fileName, index):
print("spawnWork: Entry... ")
process = Process(target=execute, args=(fileName, index, ))
process.start()
print("spawnWork: ... Exit.")
def execute(fileName, index):
print("execute: Entry... ")
#Do some long processing
print("execute: ... Exit.")
works fine from Python, but when embedded it stuck at .start() and locks.
I'm using all the relevant API calls to ensure safe GIL processing for Python. It works pretty well when not dealing with 'multiprocessing' package but locks when attempting to start another 'Process'.
Is it possible to use both Python/C++ mix and 'multiprocessing'?
Thanks
I wouldn't expect this to work, as the way multiprocessing works on Windows (where there's no fork) is to CreateProcess another copy of the same executable. And since that executable is your embedding C++ app, not the Python interpreter, you will probably have to cooperate very closely with it to make that work. You can see the relevant code in posix_spawn_win32.py.
Another potential problem is that on Windows, multiprocessing relies on a C extension module that fakes POSIX semaphores on top of Windows kernel semaphores; I haven't read through the code, but that could easily be doing something funky to GIL/threadstate and/or relying on something under the covers to share the semaphores with child Python executables.

Using resource in windows

i've got a script that uses the resource-module from python (see http://docs.python.org/library/resource.html for information). Now i want to port this script to windows. is there any alternative version of this (the python-docs are labeling it as "unix only").
if there isn't, is there any other workaround?
I'm using the following method/constant:
resource.getrusage(resource.RUSAGE_CHILDREN)
resource.RLIMIT_CPU
Thank you
PS: I'm using python 2.7 / 3.2
There's no good way of doing this generically for all "Resources"" -- hence why it's a Unix only command. For CPU speed only you can either use registry keys to set the process id limit:
http://technet.microsoft.com/en-us/library/ff384148%28WS.10%29.aspx
As done here:
http://code.activestate.com/recipes/286159/
IMPORTANT: Backup your registry before trying anything with registry
Or you could set the thread priority:
http://msdn.microsoft.com/en-us/library/ms685100%28VS.85%29.aspx
As done here:
http://nullege.com/codes/search/win32process.SetThreadPriority
For other resources you'll have to scrap together similar DLL access APIs to achieve the desired effect. You should first ask yourself if you need this behavior. Oftentimes you can limit CPU time by sleeping the thread in operation at convenient times to allow the OS to swap processes and memory controls can be done problematically to check data structure sizes.

Python - Using os.popen() to parse Unix "ls" - Problems with Killing Child Process

From my understanding, os.popen() opens a pipe within Python and initiates a new sub process. I have a problem when I run a for loop in conjunction with os.popen(). I can't seem to CTRL+C out of the loop. Here is my code:
for FILE in os.popen("ls $MY_DIR/"):
os.system("./processFile " + FILE)
Whenever I try to CTRL+C, Python will stop the ./processFile program but NOT the python program itself!
I have Google'd around and couldn't seem to find the correct answer. Some people recommend using SIGNALS (I tried... it didn't work). Another tried to use PIDs and killing child PIDs but I couldn't seem to get it.
Can someone lead me to a better example so I can stop the programming when I use CTRL+C (SIGINT) ?
I see some answer correctly recommended subprocess.check_call and the OP in a comment said
I'm getting this error:
AttributeError: 'module' object has no
attribute 'check_call'
Per the docs I just linked to, check_call is marked as:
New in version 2.5.
so it looks like the OP is using some ancient version of Python -- 2.4 or earlier -- without mentioning the fact (the current production-ready version is 2.7, and 2.4 is many years old).
The best one can recommend, therefore, is to upgrade! If 2.7 is "too new" for your tastes (as it might be considered in a conservative "shop"), 2.6's latest microrelease should at least be fine -- and it won't just give you subprocess.check_call, but also many additional feautures, bug fixes, and optimizations!-)
The behavior is correct. Ctrl+C stops the foreground process and not its parent process. Calling the shell and using ls is inappropriate here, your code should better be written as follows (untested):
import os
import subprocess
for fname in os.listdir(directory):
path = os.path.join(directory, fname)
subprocess.check_call(["./processFile", path])

Categories