Skip to content

Instantly share code, notes, and snippets.

@mottosso
Last active May 17, 2023 05:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mottosso/93399862c94f0ab4314f to your computer and use it in GitHub Desktop.
Save mottosso/93399862c94f0ab4314f to your computer and use it in GitHub Desktop.
Learn Pyblish By Example - Quickstart 1.4
"""Full Example
From https://pyblish.gitbooks.io/pyblish-by-example/content/chapters/02-quickstart.html
Usage:
Copy and run this entire file in your Maya Script Editor
"""
import os
import shutil
from datetime import datetime
import pyblish.api
import pyblish_maya
from maya import cmds
# Install Pyblish for Autodesk Maya
pyblish_maya.setup()
# ----------------------------------------------------------------------------
#
# Generate Scene
#
# ----------------------------------------------------------------------------
cmds.file(new=True, force=True)
cmds.polyCube(name="geometry")
cmds.sets(name="pointcache_SEL")
cmds.circle(name="control")
cmds.sets(name="controls_SEL")
cmds.select(["geometry", "control"])
cmds.group(name="Bruce_GRP")
cmds.select(["Bruce_GRP", "pointcache_SEL", "controls_SEL"], noExpand=True)
cmds.sets(name="Bruce_RIG")
# Save the scene
cmds.file(rename="scene.ma")
cmds.file(save=True, type="mayaAscii")
# ----------------------------------------------------------------------------
#
# Publish
#
# ----------------------------------------------------------------------------
class CollectRig(pyblish.api.ContextPlugin):
"""Discover and collect available rigs into the context"""
order = pyblish.api.CollectorOrder
def process(self, context):
for node in cmds.ls(sets=True):
if not node.endswith("_RIG"):
continue
name = node.rsplit("_", 1)[0]
instance = context.create_instance(name, family="rig")
# Collect associated nodes
members = cmds.sets(node, query=True)
cmds.select([node] + members, noExpand=True)
instance[:] = cmds.file(
constructionHistory=True,
exportSelected=True,
preview=True,
force=True)
class ValidateRigContents(pyblish.api.InstancePlugin):
"""Ensure rig has the appropriate object sets"""
order = pyblish.api.ValidatorOrder
families = ["rig"]
def process(self, instance):
assert "controls_SEL" in instance, "%s is missing a controls set" % instance
assert "pointcache_SEL" in instance, "%s is missing a pointcache set" % instance
class ExtractRig(pyblish.api.InstancePlugin):
"""Serialise valid rig"""
order = pyblish.api.ExtractorOrder
families = ["rig"]
hosts = ["maya"]
def process(self, instance):
context = instance.context
dirname = os.path.dirname(context.data["currentFile"])
name, family = instance.data["name"], instance.data["family"]
date = datetime.now().strftime("%Y%m%dT%H%M%SZ")
# Find a temporary directory with support for publishing multiple times.
tempdir = os.path.join(dirname, "temp", date, family, name)
tempfile = os.path.join(tempdir, name + ".ma")
self.log.info("Exporting %s to %s" % (instance, tempfile))
if not os.path.exists(tempdir):
os.makedirs(tempdir)
cmds.select(instance, noExpand=True) # `instance` a list
cmds.file(tempfile,
type="mayaAscii",
exportSelected=True,
constructionHistory=False,
force=True)
# Store reference for integration
instance.set_data("tempdir", tempdir)
class IntegrateRig(pyblish.api.InstancePlugin):
"""Copy files to an appropriate location where others may reach it"""
order = pyblish.api.IntegratorOrder
families = ["rig"]
def process(self, instance):
assert instance.data("tempdir"), "Can't find rig on disk, aborting.."
self.log.info("Computing output directory..")
context = instance.context
dirname = os.path.dirname(context.data("currentFile"))
root = os.path.join(dirname, "public")
if not os.path.exists(root):
os.makedirs(root)
version = "v%03d" % (len(os.listdir(root)) + 1)
src = instance.data("tempdir")
dst = os.path.join(root, version)
self.log.info("Copying %s to %s.." % (src, dst))
shutil.copytree(src, dst)
self.log.info("Copied successfully!")
pyblish.api.register_plugin(CollectRig)
pyblish.api.register_plugin(ValidateRigContents)
pyblish.api.register_plugin(ExtractRig)
pyblish.api.register_plugin(IntegrateRig)
# Run
import pyblish.util
pyblish.util.publish()
@juggernate
Copy link

When I try to run this on Win7 x64 in Maya2106 I get:

#   File "...\pyblish-win\lib\pyblish\modules\pyblish-base\pyblish\plugin.py", line 844, in register_plugin
#     "with this host" % plugin)
# TypeError: Plug-in <class '__main__.ExtractRig'> is not compatible with this host //

@mottosso
Copy link
Author

mottosso commented Apr 8, 2016

Thanks for reporting this.

This is the intended behaviour, and the reason this is happening is because the plug-in requires Maya but Maya has not been registered with Pyblish.

The registration happens automatically with the Pyblish Maya integration, when calling the pyblish_maya.setup() function, and it doesn't look like it has been properly set up. You can work around it by registering the host yourself, using pyblish.api.register_host("maya"), but it is recommended that you use the integration because it also has a few fundamental plug-ins that external Pyblish projects may come to assume, such as Pyblish Magenta.

Here's a guide for this attribute.


Note that though gists support comments, they don't support notifications. So feel free to make an issue in the book GitHub project for future problems.

I openend up an issue to make this problem more discoverable.

@mottosso
Copy link
Author

mottosso commented Jun 7, 2016

I've updated the file to drop the dependency on the graphical user interface, it now works with just pyblish-base.

@davidlatwe
Copy link

Hi, after run this, I got

Can't find rig on disk, aborting..

and I print out the context result, I found

{'action': None,
'duration': 0.0,
'error': KeyError('currentFile',),
'instance': pyblish.plugin.Instance("Bruce"),
'plugin': <class 'pyblish.plugin.ExtractRig'>,
'records': [],
'success': False}

seems lost one line in CollectRig plugin

context.data["currentFile"] = cmds.file(q= 1, sn= 1)

after I add this line it worked.

Is this fix correct ? Thanks.

@mottosso
Copy link
Author

mottosso commented Aug 5, 2017

Thanks for reporting this. The reason you are seeing this is because you need Pyblish Maya in order to run this example. currentFile is added by one of the plugins included in that integration.

@davidlatwe
Copy link

Oh I see that, Thanks!

@Jeremyball
Copy link

Hi, I'm seeing an Error when running the above code in MAYA 2020, on both OSX and Win10.

Runs fine in MAYA 2018 Win10 and MAYA 2019 OSX

# Error: 'module' object has no attribute 'QStringListModel'
# Traceback (most recent call last):
#   File "<maya console>", line 15, in <module>
#   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyblish_maya/__init__.py", line 3, in <module>
#     from .lib import (
#   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyblish_maya/lib.py", line 16, in <module>
#     from .vendor.Qt import QtWidgets, QtGui
#   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyblish_maya/vendor/Qt.py", line 446, in <module>
#     cli(sys.argv[1:]) if __name__ == "__main__" else init()
#   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyblish_maya/vendor/Qt.py", line 393, in init
#     binding = binding()
#   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pyblish_maya/vendor/Qt.py", line 239, in _pyside2
#     _remap(QtCore, "QStringListModel", QtGui.QStringListModel)
# AttributeError: 'module' object has no attribute 'QStringListModel' # 

@mottosso
Copy link
Author

Thanks for reporting this @Jeremyball. Looks like an outdated version of Qt.py, could you try and copy/paste the latest version into that file you see there? If that's the cause, we should be able to update pyblish_maya in the same way and all shall be well. In fact, if it does work you're welcome to copy/paste it into pyblish_maya and submit a PR and fix it for all.

@Michaelredaa
Copy link

I fix this issue by replacing QStringListModel by str in this form _remap(QtCore, "QStringListModel", str)

@frostfyre
Copy link

Running from PyCharm with mayapy.exe (2022) as the interpreter, pyblish-base and pyblish-maya installed, I get the following when running this script:

Traceback (most recent call last): File "C:\Program Files\Autodesk\Maya2022\Python37\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "C:\Users\frost\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\222.4167.33\plugins\python\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Users\frost\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\222.4167.33\plugins\python\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "D:\dev\tech-art\maya-toolkit-dev\src\scripts\pforest\pyblish_tests\rig_example.py", line 12, in <module> import pyblish_maya File "C:\Users\frost\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\222.4167.33\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Program Files\Autodesk\Maya2022\Python37\lib\site-packages\pyblish_maya\__init__.py", line 1, in <module> from version import * File "C:\Users\frost\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\222.4167.33\plugins\python\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'version'

@frostfyre
Copy link

I should note that simply attempting to import pyblish-maya yields the same result.

@mottosso
Copy link
Author

This looks like a Python 3 issue, and I would double-check you've got the latest current version of pyblish-maya, because this one does appear to work.

You can install directly from GitHub with..

pip install git+https://github.com/pyblish/pyblish-maya.git

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment