def process(self, context):
from maya import cmds
from avalon import maya
assert all(result["success"] for result in context.data["results"]), (
"Integration failed, aborting.")
maya.lock()
with maya.lock_ignored():
cmds.file(save=True, force=True)
python类file()的实例源码
def process(self, context):
"""Inject the current working file"""
current_file = cmds.file(query=True, sceneName=True)
context.data['currentFile'] = os.path.normpath(current_file)
def load_data(file_path):
"""Load a skeleton hierarchy from the given json data file. No nodes will be created in Maya.
:param file_path: Json file on disk.
:return: The hierarchy data loaded from disk.
"""
fh = open(file_path, 'r')
data = json.load(fh)
fh.close()
return data
def load(file_path=None):
"""Load a skeleton hierarchy from the given json data file and generates the hierarchy in Maya.
:param file_path: Json file on disk.
:return: The hierarchy data loaded from disk.
"""
if file_path is None:
file_path = cmds.fileDialog2(fileFilter='Skeleton Files (*.json)', dialogStyle=2, caption='Export Skeleton',
fileMode=1, returnFilter=False)
if file_path:
file_path = file_path[0]
else:
return
data = load_data(file_path)
create_node(data)
return data
def set_file_new(value):
"""Set whether a new file should be created after each test.
@param value: True or False
"""
Settings.file_new = value
def tearDown(self):
if Settings.file_new and CMT_TESTING_VAR not in os.environ.keys():
# If running tests without the custom runner, like with PyCharm, the file new of the TestResult class isn't
# used so call file new here
cmds.file(f=True, new=True)
def test_get_and_rebuild_data(self):
data = skeleton.get_data(self.group)
cmds.file(new=True, f=True)
skeleton.create_node(data)
self.assert_hierarachies_match()
def test_export_and_import_data(self):
json_file = self.get_temp_filename('skeleton.json')
skeleton.dump(self.group, json_file)
cmds.file(new=True, f=True)
skeleton.load(json_file)
self.assert_hierarachies_match()
def new_scene():
checkState()
return cmds.file(new=True, f=True)
def save_scene_as(path = None, file_name = None):
if os.path.exists(path):
if file_name:
fullpath = os.path.join(path,file_name)
cmds.file(rename = fullpath)
return cmds.file(s=True, type="mayaAscii")
def open_scene(path = None):
if os.path.exists(path):
checkState()
insert_recent_file(path)
opend = cmds.file(path, o = True, f = True, esn = True)
logging.info("{}".format(opend))
return opend
def current_open_file():
return cmds.file(q=True,sn=True)
def checkState():
# check if there are unsaved changes
fileCheckState = cmds.file(q=True, modified=True)
# if there are, save them first ... then we can proceed
if fileCheckState:
# This is maya's native call to save, with dialogs, etc.
# No need to write your own.
if dlg.warning("warning", "Scene Not Saved", "Scene Not Saved, Do you want to save it first?"):
cmds.SaveScene()
pass
else:
pass
def import_scene(path = None):
if os.path.exists(path):
namesspace = files.file_name_no_extension(files.file_name(path))
return cmds.file(path, i = True, f = True, ns = namesspace, esn = False)
def new_scene_from_selection(project_path = None, mode = "include"):
temp_file = os.path.join(project_path, "scenes", "temp_%s.ma"%(id_generator()))
logging.info(temp_file)
sel = cmds.ls(sl=True)
if len(sel)>0:
if mode == "include":
saved_file = cmds.file(temp_file, type='mayaAscii', exportSelected=True, expressions=True, constraints=True, channels=True, constructionHistory=True, shader=True)
if mode == "exclude":
saved_file = cmds.file(temp_file, type='mayaAscii', exportSelected=True, expressions=False, constraints=False, channels=False, constructionHistory=False, shader=True)
if saved_file:
open_scene(saved_file)
return saved_file
return None
def open_file(file_path, file_type):
u"""????????????
:param file_path: ??????
:type file_path: unicode
:param file_type: ???????
:type file_type: unicode
"""
cmds.file(force=True, new=True)
mel.eval('openRecentFile("{0}", "{1}");'.format(file_path, file_type))
def get_current_scenename():
path = cmds.file(query=True, sceneName=True)
if path:
return os.path.splitext(os.path.basename(path))[0]
return None
def open_file(filepath):
"""Open file using OS default settings"""
if sys.platform.startswith('darwin'):
subprocess.call(('open', filepath))
elif os.name == 'nt':
os.startfile(filepath)
elif os.name == 'posix':
subprocess.call(('xdg-open', filepath))
else:
raise NotImplementedError("OS not supported: {0}".format(os.name))
def _fix_playblast_output_path(filepath):
"""Workaround a bug in maya.cmds.playblast to return correct filepath.
When the `viewer` argument is set to False and maya.cmds.playblast does not
automatically open the playblasted file the returned filepath does not have
the file's extension added correctly.
To workaround this we just glob.glob() for any file extensions and assume
the latest modified file is the correct file and return it.
"""
# Catch cancelled playblast
if filepath is None:
log.warning("Playblast did not result in output path. "
"Playblast is probably interrupted.")
return
# Fix: playblast not returning correct filename (with extension)
# Lets assume the most recently modified file is the correct one.
if not os.path.exists(filepath):
directory = os.path.dirname(filepath)
filename = os.path.basename(filepath)
# check if the filepath is has frame based filename
# example : capture.####.png
parts = filename.split(".")
if len(parts) == 3:
query = os.path.join(directory, "{}.*.{}".format(parts[0],
parts[-1]))
files = glob.glob(query)
else:
files = glob.glob("{}.*".format(filepath))
if not files:
raise RuntimeError("Couldn't find playblast from: "
"{0}".format(filepath))
filepath = max(files, key=os.path.getmtime)
return filepath
def capture_scene(options):
"""Capture using scene settings.
Uses the view settings from "panel".
This ensures playblast is done as quicktime H.264 100% quality.
It forces showOrnaments to be off and does not render off screen.
:param options: a collection of output options
:type options: dict
:returns: Full path to playblast file.
:rtype: str
"""
filename = options.get("filename", "%TEMP%")
log.info("Capturing to: {0}".format(filename))
options = options.copy()
# Force viewer to False in call to capture because we have our own
# viewer opening call to allow a signal to trigger between playblast
# and viewer
options['viewer'] = False
# Remove panel key since it's internal value to capture_gui
options.pop("panel", None)
path = capture.capture(**options)
path = _fix_playblast_output_path(path)
return path