In this Module we get the list of current processes running in the OS. I used this Library
psutilIn the module when we call the function getCurrProcesses(), returns a list of all the processes with name and process id in dictionary format. Then I write them into an XML file.
The XML is changed :-
<?xml version="1.0" ?>
<pinfo>
<!--List of Running Processes in the OS-->
<PROCESS pid="PID">
PNAME
</PROCESS>
</pinfo>
So here's the code :-
"""
Created on Aug 27, 2014
@author: psychocoder
"""
import os, sys
import psutil
from xml.etree.ElementTree import Element, Comment, SubElement
from pinn.Constants import Constants
from pinn.FunctionUtil import FuncUtil
__author__ = "Animesh Shaw"
__copyright__ = "Copyright (C) 2014 Animesh Shaw"
__license__ = "Apache License"
__version__ = "1.0"
class OSCurrProcesses():
"""
Creates an XML file with the current processes running in the operating System
"""
def __init__(self):
"""
Initializes the necessary variables.
"""
self.__cons = Constants()
@staticmethod
def getCurrProcesses():
"""
Get the list of current running processes.
@return: Returns the process name and process id"s of the current
running processes as a list of dictionary of PID and PNAME
@rtype: list
"""
pinfo = []
for proc in psutil.process_iter():
try:
pinfo.append(proc.as_dict(attrs=["pid", "name"]))
except psutil.NoSuchProcess:
pass
else:
continue
return pinfo
def writeProcessesToXML(self, pinfo=[]):
"""
Writes the data obtained about current running processes into
an XML file
@param pinfo: The list of processes
"""
if not pinfo and type(pinfo) != list:
raise (TypeError, AttributeError)
sys.exit()
funcutil = FuncUtil()
rootElement = Element("pinfo")
rootElement.append(Comment("List of Running Processes in the OS"))
for item in pinfo:
child = SubElement(rootElement, "PROCESS", attrib={"pid" : str(item.get("pid"))})
child.text = item.get("name")
file_loc = self.__cons.OSDATA_LOC + "/pinfo_data.xml"
if os.path.exists(file_loc):
with open(file_loc, mode="w") as f:
f.writelines(str(funcutil.prettifyXML(rootElement)))
f.close()
else:
raise OSError("Unable to Write data. Path invalid or Premission denied.")
def main():
ins = OSCurrProcesses()
ins.writeProcessesToXML(ins.getCurrProcesses())
if __name__ == "__main__":
main()
Output :- Thank you.