Getting the current project context/self.shotgun in the python shell?

Whats the most easiest and preffered way to get the project context from the python shell?

Im trying to use self.shotgun as api commands in the python shell but it doesnt work like it would in a app for example.

Is there a unified/preffered way to get basic values for the context when we are launching something from within the Loaded project in shotgun desktop?

1 Like

To make it more explicit, from the python shell I currently do this so the code will work regardlessm just questioning if there is a more unified way?

##########################################################

Get Project Context

##########################################################
try:
multi_launchapp = self.parent
project = multi_launchapp.context.project[“name”]
os.environ[“SHOTGUN_CURRENT_PROJECT”] = project
except:
project = “Pipeline”`

print “\nCurrent project:”, project
##########################################################

1 Like

Hi Ricardo

From your code snippet it looks as though that code might be running from a tk-multi-launchapp hook, the reason I say that is that you have multi_launchapp = self.parent, is that correct?

As you found the Application object has a reference to the context.
Also the engine has a reference to the current context as well.

The best way to get the current session’s context would be to run the following:

# if running in a hook, self.parent will return the parent Application object that is calling the hook.
# https://developer.shotgunsoftware.com/tk-core/core.html#sgtk.Hook.parent
# From the Application you can get the current engine, which manages and holds the current context.
current_engine = self.parent.engine
current_context = current_engine.current_context

print("Project:",current_context.project["name"])

If your code is not running in a hook but an engine is present (though this would also work from within the hook as well), you could run the following:

# Get a handle to the currently running engine.
current_engine = sgtk.platform.current_engine()
current_context = current_engine.context

print("Project:",current_context.project["name"])

Does that help?

1 Like

I think that may solve different problems, I was just thinking about how to grab the current project from the python shell in shotgun desktop.
I like to test snippets of code in there.

1 Like

You actually get given the current context for free in the Shotgun Python Console, it’s stored in the predefined context variable
Shotgun__Shotgun_Python_Console

That said the current_engine = sgtk.platform.current_engine()
current_context = current_engine.context would work here as well.

3 Likes

Doh!

Thanks :smiley:

Just trying to unify the code a bit as this is all just dependent on whatever project I’m in :wink:

3 Likes