accessing an already running process, with python

  • Last Update :
  • Techknowledgy :

If you're running mayabatch from the command line or a bat file, you can funnel stdout to a file with a > character:

  mayabatch.exe "file.ma" > log.txt

OTOH If you're doing it from python, it's a little tougher unless you don't mind having your python script idled until the mayabatch completes. The usual subprocess recipe, which uses popen.communicate() is going to wait for an end-of-process return code:

 test = subprocess.Popen(["mayabatch.exe", "filename.mb"], stdout = subprocess.PIPE)
 print test.communicate()[0]

works but won't report until the process dies. But you calling readlines on the process's stdout will trigger the process and report it one line at a time:

 test = subprocess.Popen(["mayabatch.exe", "filename.mb"], stdout = subprocess.PIPE)
 reader = iter(test.subprocess.readlines, "")
 for line in reader:
    print line

Suggestion : 2

Last Updated : 29 Dec, 2020

1._
pip install wmi

Output: 
 

3196 RuntimeBroker.exe
3524 ShellExperienceHost.exe
3548 SearchIndexer.exe
3796 SearchUI.exe
4136 IDMan.exe
4368 IEMonitor.exe
4488 notepad.exe
2616 SettingSyncHost.exe
4212 dasHost.exe
4664 AdaptiveSleepService.exe
4716 svchost.exe
5412 chrome.exe
1376 chrome.exe
1280 cmd.exe
4928 conhost.exe
5596 py.exe
5060 python.exe
1508 WmiPrvSE.exe

Explanation:
Firstly, we initialize the WMI() function of wmi library. This allows us to use the functions found inside it such as WMI.Win32_Service, WMI.Win32_Process, WMI.Win32_Printjob which are designed to perform different tasks. We would be using the WMI.Win32_Process function in order to get the list of running processes on the system. Then we called the function WMI.Win32_Process() to get the running processes, iterated through each process and stored in variable process. Then we obtained the ProcessID (pid) and ProcessName (name) of the process using the associated attributes. We used F-strings for the output in order to add padding to the output to align it properly. 
  
Method 2:
In this method, we would be using a command found inside the Windows Command Processor (cmd.exe) under the name WMIC ( Windows Management Instrumentation Command line) in order to get the desired result. WMIC is a commandline utility that allows users to performs Windows Management Instrumentation (WMI) operations with a command prompt. For the purpose of getting running processes, we would be executing the command:
 

wmic process get description, processid

Suggestion : 3

In this article we will discuss a cross platform way to get a list of all running processes in system and then sort them by memory usage.,Python provides a cross platform library psutil to fetch sunning system details like process and system details.,Process class provides the memory info of process, it fetches the virtual memory usage from it, then appends the dict for each process to a list. In the end sort the list of dictionary by key vms, so list of process will be sorted by memory usage.,Each process object yielded by process_iter() has information about that running process like, id , name, user name, parent id, memory usage and cpu usage etc.

To install psutil using pip execute following command,

pip install psutil

import psutil

psutil provides a function to iterate over all the running process i.e.

psutil.process_iter(attrs = None, ad_value = None)

import psutil

def getListOfProcessSortedByMemory():
   ''
'
Get list of running process sorted by Memory Usage ''
'
listOfProcObjects = []
# Iterate over the list
for proc in psutil.process_iter():
   try:
   # Fetch process details as dict
pinfo = proc.as_dict(attrs = ['pid', 'name', 'username'])
pinfo['vms'] = proc.memory_info().vms / (1024 * 1024)
# Append dict to list
listOfProcObjects.append(pinfo);
except(psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
   pass

# Sort list of dict by key vms i.e.memory usage
listOfProcObjects = sorted(listOfProcObjects, key = lambda procObj: procObj['vms'], reverse = True)

return listOfProcObjects

Let’s call this function and print top 5 process by memory usage i.e.

listOfRunningProcess = getListOfProcessSortedByMemory()

for elem in listOfRunningProcess[: 5]:
   print(elem)

Suggestion : 4

In this tutorial, we'll learn how to detect a process is running properly, and depending on the outcome, we'll stop/re-run the process. Our platform is Windows Server 2012, and it will most likely to work on other Windows products as well. The script is written in Python.,To run a scheduled task, we can follow the logic below, and coding it depending on the cases:,displays verbose task information in the output. The list r gets all the processes one element per line, and the getTasks() returns a process has the process that has the program name in the string. If no such a process with the given name, it returns empty list.,schtasks enables an administrator to create, delete, query, change, run, and end scheduled tasks on a local or remote computer. Running Schtasks.exe without arguments displays the status and next run time for each registered task. (Schtasks.exe)

Here is the code for detecting the status of a program:

import os

def getTasks(name):
   r = os.popen('tasklist /v').read().strip().split('\n')
print('# of tasks is %s' % (len(r)))
for i in range(len(r)):
   s = r[i]
if name in r[i]:
   print('%s in r[i]' % (name))
return r[i]
return []

if __name__ == '__main__':
   ''
'
This code checks tasklist, and will print the status of a code ''
'

imgName = 'dwm.exe'

notResponding = 'Not Responding'

r = getTasks(imgName)

if not r:
   print('%s - No such process' % (imgName))

elif 'Not Responding' in r:
   print('%s is Not responding' % (imgName))

else:
   print('%s is Running or Unknown' % (imgName))

The line in the getTasks():

tasklist / v

A sample output looks like this:

C: \ > python h.py
# of tasks is 71
dwm.exe in r[i]
dwm.exe is Running or Unknown