Launching From a Script

From PyMOLWiki
Jump to: navigation, search

The recommended way to run PyMOL-Python scripts is by using PyMOL as the interpreter. This is supported by all versions of PyMOL, including the pre-compiled bundles provided by Schrödinger.

Example from a shell:

shell> pymol -cq

With arguments (sys.argv becomes ["", "foo", "bar"]):

shell> pymol -cq -- foo bar

Example from a running PyMOL instance:

PyMOL> run

For advanced users, Open-Source PyMOL (as well as the Schrödinger-provided "Mac alternative X11-only build") also allows to run PyMOL from an existing Python process. After importing the pymol module, PyMOL's event loop has to be started with a call to pymol.finish_launching().


Since PyMOL 1.7.4, the following form is sufficient:

import pymol
pymol.finish_launching(['pymol', '-q'])

Before 1.7.4, either "-K" was needed as an additional argument, or arguments had to be assigned to __main__.pymol_argv or pymol.pymol_argv.

Example 1

Here is an example script that launches PyMol for stereo viewing on a VisBox. It runs PyMol fullscreen stereo, and disables the internal gui. The environment (PYTHON_PATH and PYMOL_PATH) must already be set up for this example to work (see Example 2 below for how to setup within the script).

#!/usr/bin/env python
# Tell PyMOL to launch quiet (-q), fullscreen (-e) and without internal GUI (-i)
import __main__
__main__.pymol_argv = [ 'pymol', '-qei' ]
import pymol
# Call the function below before using any PyMOL modules.
from pymol import cmd
cmd.set('stereo_shift', 0.23)
cmd.set('stereo_angle', 1.0)

Example 2

This script launches PyMOL without any GUI for scripting only. It enables tab-completion on the python command line and does the PyMOL environment setup (you need to adjust the moddir variable!). Hint: You may save this as "pymol-cli" executable.

#!/usr/bin/python2.6 -i

import sys, os

# autocompletion
import readline
import rlcompleter
readline.parse_and_bind('tab: complete')

# pymol environment
sys.path.insert(0, moddir)
os.environ['PYMOL_PATH'] = os.path.join(moddir, 'pymol/pymol_path')

# pymol launching: quiet (-q), without GUI (-c) and with arguments from command line
import pymol
pymol.pymol_argv = ['pymol','-qc'] + sys.argv[1:]
cmd = pymol.cmd


PyMOL captures sys.stdout and sys.stderr, to control it with it's own feedback mechanism. To prevent that, save and restore both streams, e.g.:

import sys
stdout = sys.stdout
stderr = sys.stderr
pymol.finish_launching(['pymol', '-xiq'])
sys.stdout = stdout
sys.stderr = stderr

See Also