0

Is there a way to know which application I'm running a python script from?

I can run python from multiple sources, like Textmate, Sublime Text 2 or Terminal (I'm on Mac OSX). How can I know, exactly which tool launched the current python app.

I've tried looking into the os and inspect modules, but couldn't find the solution.

4
  • what have you tried? if you do os.system("Textmate") then it is obvious what you run... Commented Jan 9, 2013 at 13:24
  • 1
    He is asking the reverse question... where is the python instance launched from... Commented Jan 9, 2013 at 13:28
  • I'm curious why you need to know this, because it shouldn't matter how its launched. Commented Jan 9, 2013 at 13:30
  • I'm using an application with some modules embedded and extra functionality that I can't get from other apps. And I want my code to know which app run in order to do things one way or other. I need the code cross-app. Commented Jan 9, 2013 at 13:57

2 Answers 2

1

You can use psutil to do this sort of thing in a fairly cross-platform way:

import psutil
import os
my_process = psutil.Process(os.getpid())
parent = my_process.parent
print "Parent process name: " + parent.name

From the psutil documentation:

It currently supports Linux, Windows, OSX and FreeBSD, both 32-bit and 64-bit, with Python versions from 2.4 to 3.3 by using a single code base.

As well as the name you can get the executable path (which might be more useful if you're selecting from a list of options) and also the full command-line with which it was invoked. You can also get the username who ran the process. See the psutil classes documentation for details of the parameters and the platforms on which they're available.

As an aside, if at all possible I would structure your code so that you don't have to modify your behaviour according to the calling application - it would be much preferable to have the calling application pass in a parameter which modifies the behaviour of the shared code. However, I appreciate that sometimes other concerns take precedence over cleanliness of code, so psutil should enable you to do what you requested.

Sign up to request clarification or add additional context in comments.

Comments

0

If you're happy to stay specific to unix and then you can get the parent PID of the process with os.getppid(). If you wanted to translate it back to a program id, you could can run a subprocess to use the relevant OS-specific PID-to-useful-data tool (odds on - ps)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.