I’m having an issue using subprocess.Popen inside a maya script.
I’ve used it before in a simple python script but it’s the first time inside maya.
Anyway I’m trying to write a little script to launch batch render with vray though a button.
Here’s the code for the kickoff function:
def kickoff():
# Check for unsaved changes
scene = cmds.file(q=True, sceneName=True)
if not scene:
cmds.warning("Please save the scene before rendering.")
return
if cmds.file(q=True, modified=True):
result = cmds.confirmDialog(title="Save Changes?", message="The scene has unsaved changes. Save before rendering?", button=["Save", "Don't Save", "Cancel"], defaultButton="Save", cancelButton="Cancel", dismissString="Cancel")
if result == "Save":
cmds.file(save=True)
elif result == "Cancel":
return
render_exe_path = Path(os.environ.get("MAYA_LOCATION", "")) / "bin" / "Render.exe"
print(render_exe_path)
cmd = f'"{render_exe_path}" -r vray "{scene}"'
print(cmd)
subprocess.Popen(cmd, shell=True)
Any clue to this issue would be greatly appreciated!
Thanks!
You say you have “an issue”, but you never actually said what the issue is…. No worries, I can get you started.
So … Is it crashing immediately? Do you get a return code? You’re not storing the Popen object in a variable. You should try returning that from your function and seeing if there’s any information you can get from there. Definitely check the docs, and maybe try to use the dir and help functions.
There can be a LOT to managing subprocesses, especially when starting form different environments, and depending how generic you want your system to be.
And from my experience, if all else fails, it always seems to be the env flag to Popen. Seriously save this for last because debugging this is a pain in the butt. But I’ve had to do things like this multiple times: Try writing the external os.environ to a file (probably json) and load it in maya’s python, and pass that to your popen. If that makes it work, then you should narrow down which variable is breaking things (It’s probably PATH), and possibly which parts of the variable’s value are causing the issue.
Final note: It’s generally a bad idea to use shell=True. Check the python docs for an example of how to go without it.
subprocess.run() returns a CompletedProcess object which you can introspect for issues.
subprocess.run returns a CompletedProcess objetc which you can introspect for issues.
import subprocess
def run_cmd(cmd, raise_errors=False):
result = None
print(cmd)
completed_process = subprocess.run(
cmd, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW, shell=True
)
if completed_process.returncode != 0:
msg = ("cmd '{}' errored out:\n\t{}".format(cmd, completed_process))
if raise_errors:
raise RuntimeError(msg)
if completed_process.stderr:
result = completed_process.stderr
print("STD ERROR:")
print(result)
if completed_process.stdout:
result = completed_process.stdout
print("SUCESS:")
print(result)
return result