Only call function if PyMOL running

519 Views Asked by At

I have a script that performs some calculations on a protein. When it's finished, a method imports the pymol module, and uses the pymol.cmd API to display results in a PyMOL session. The process is something akin to the following:

def display_results(results, protein_fn):
    import pymol
    pymol.cmd.load(protein_fn)
    pymol.cmd.alter(...)
    ...

protein_fn = "1abc.ent"
results = analyze_protein(protein_fn)
display_results(results, protein_fn)

However, my script doesn't necessarily need to display the results in PyMOL, and I'd like this to only be done if PyMOL is installed and running.

It's easy to check if PyMOL is installed (I can just try: import pymol), but is there a way to check if there's an active PyMOL session to display results in?

2

There are 2 best solutions below

1
On BEST ANSWER

I'm not an expert on PyMOL (haven't ever scripted it) but I see 2 possible ways:

  1. Do something trivial that requires an open PyMOL session and catch exceptions
  2. Look at process names (something like os.system("ps ux | grep -i pymol"))

First way is better, second is a dirty hack.

1
On

I usually just do something like:

try:
    import pymol
    pymol_imported = True
except:
    pymol_imported = False

Then

if pymol_imported:
    display_results(...)

I don't know if that's Python "best practices", but PyMol scripts are usually just quick, one-off things in most cases, anyways.