Need to find which program called the python script

早过忘川 提交于 2019-12-25 18:49:07

问题


I am using a build system(waf) which is a wrapper around python. There are some programs(perl scripts,exe's etc) calling the python build system. When I execute the build scripts from cmd.exe, I need to find out the program that called it. My OS is windows 7. I tried getting the parent PID in a python module and it returns "cmd" as PPID and "python.exe" as PID, so that approach did not help me in finding what I am looking for.

I believe I should be looking at some stacktraces on a OS level, but am not able to find how to do it. Please help me with the approach I should take or a possible code snippet. I just need to know the name of the script or program that called the system, example caller.perl, callload.exe

Thank you


回答1:


Though I am not sure why it would be needed but this is a fun problem in itself, so here are few tips, once you have parent PID loop thru processes and get name e.g.

using WMI

import wmi
c = wmi.WMI ()

for process in c.Win32_Process ():
    if process.ProcessId == ppid:
      print process.ProcessId, process.Name

I think you can do same thing using win32 API, e.g.

processes = win32process.EnumProcesses()
for pid in processes:
    if pid == ppid:
       handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,
False, pid)
       exe = win32process.GetModuleFileNameEx(handle, 0)  

This will work for simple cases when progA directly executes progB but if there is a long chain of child process in between, it may not be good solution. Best way for a generic case would be for calling program to tell his identity by passing it as argument e.g.

progB --calledfrom progA



回答2:


modify the python script to add an argument to it, stating which file called it. then log it into a logger file. all scripts calling it will have to identify themselves to the python script via the argument vector.

For example:

foo.pl calls yourfile.py as:

yourfile.py /path/to/foo.pl

yourfile.py:

def main(argv):
   logger.print(argv[1])



回答3:


I was able to use process explorer to see the chain of processes called and was able to retrieve the name by just traversing the parent. Thanks for all who replied.



来源:https://stackoverflow.com/questions/12978013/need-to-find-which-program-called-the-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!