How do you find the file that is running or debugging a python file (i.e if you run your python file in Visual studio code, it will output "Code.exe", which is the name of the exe file that VS code runs on)
CodePudding user response:
the answer is a mix of python os.getppid()
to get the parent id, and psutil to get the executable name
import os
import psutil
parent_id = os.getppid()
for proc in psutil.process_iter():
if proc.pid == parent_id:
print(proc)
print(proc.name())
break
psutil.Process(pid=11172, name='pycharm64.exe', status='running', started='21:30:50')
pycharm64.exe
and yes that code ran in pycharm.
Edit: in Vscode, because Vscode runs powershell as a child then runs python from it, it gets more involved, and you have to climb to the last grandparent, but using the solution from this psutil gist with some modifications.
import os
import psutil
def get_parent_process(limit=10):
depth = 0
this_proc = psutil.Process(os.getpid())
next_proc = psutil.Process(this_proc.ppid())
while depth < limit:
try:
next_proc = psutil.Process(next_proc.ppid())
except psutil.NoSuchProcess as e:
return next_proc.name()
depth = 1
return next_proc.name()
print(get_parent_process())
Code.exe