On 01Jun2019 10:02, nathan tech <nathan-t...@hotmail.com> wrote:
Now it has been mentioned, I do recall, on linux, briefly playing with
psutil to retrieve memory values for a few tasks I keep running on my
server.

To that end, I think I now know roughly what to do.


Something like this:

import psutil
import os

path=os.getcwd()+"\\program.exe"

Remark: try:

 r'\program.exe'

instead of:

 "\\program.exe"

because backslash escapes have meaning inside single or double quotes it is generally more reliable to use raw strings (r'....') for such strings to avoid accidents.

slist=[]
for x in psutil.process_iter():
 if(x.exe()==path):
  slist.append([x, x.create_time]_)

r.sort() # not sure how to sort by second element, but I'd sort the list
by start time

list.sort() and sorted() accept an optional key= parameter which is a function that takes an element and returns the sort key. For example (untested):

 r.sort(key=lambda x: x[1])

to sort on x[1].

if(len(r)>1):

Stylisticly we tend to just write:

 if r:

It is a convention in Python that collections (such as lists) are "false" if they are empty. Urr, I see you said >1, not >0; this remark probably isn't relevant. But you could drop the outer brackets, not needed in Python:

 if len(r) > 1:

It sounds like your "task" is then a running instance of "program.exe", yes? In that case the usual practive is to keep a "pid file" around with a distinctive pathname associated with the task. That is just a text file containing the process id of the task program.

So rather than iterating over the process list with psutils (which will show you _other_ instances of program.exe, perhaps being run for another purpose), you just read the pid from the pid file and see if it is running. If it is, assume the task is already active.

Untested incomplete example:

 pid_filepath = 'taskname.pid'
 try:
   pid = int(open(pid_filepath).read().strip())
   os.kill(pid, 0)
 except (OSError, ValueError):
   # missing pid file, invalid contents)
   running = False
 else:
   running = True

The "os.kill(pid, 0)" is a UNIX specific idiom for testing for a process; you can send signal 0 to a process you own successfully (the process itself never sees it); it will fail if the process doesn't exist or isn't yours. There should be a Windows equivalent for probing a process.

The converse part where you start the process includes this:

 P = subprocess.Popen(.....)   # start the program
 with open(pid_filename, 'w') as pidf:
   print(P.pid, file=pidf)

to update the process id file.
Cheers,
Cameron Simpson <c...@cskk.id.au>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to