Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active August 10, 2022 12:40
Show Gist options
  • Save internetimagery/c0580fb02422af926385 to your computer and use it in GitHub Desktop.
Save internetimagery/c0580fb02422af926385 to your computer and use it in GitHub Desktop.
Convert Python code to Mel (using mel's python interpreter)
#!/usr/bin/env python
# Python to Mel converter
# Allows running of Python code by dragging into the Maya viewport
# Created 21/04/2015
# Jason Dixon
# jason.dixon.email@gmail.com
# internetimagery.com
# Usage
# cat <inputFile> | py2mel.py > <outputFile>
# OR
# py2mel.py -input <inputFile> -output <outputFile>
try:
from io import StringIO
except ImportError:
from cStringIO import StringIO
import tokenize
import argparse
import datetime
import sys
parser = argparse.ArgumentParser(
description="Convert Python file to Melscript (using python interpreter).",
epilog="Use either standard in and out, the -input -output flags or a combination of both. ie: cat INPUTFILE | py2mel.py > OUTPUTFILE")
parser.add_argument("-i", "--input", help="Input file for processing.", type=argparse.FileType('r'))
parser.add_argument("-o", "--output", help="Output file for processing.", type=argparse.FileType('w'))
parser.add_argument("-s", "--shelf", help="Optional! Name to give to shelf icon if dropping causes shelf icon.", type=str)
args = parser.parse_args()
def remove_comments_and_docstrings(source):
"""
http://stackoverflow.com/a/2962727
"""
io_obj = StringIO(source)
out = ""
prev_toktype = tokenize.INDENT
last_lineno = -1
last_col = 0
for tok in tokenize.generate_tokens(io_obj.readline):
token_type = tok[0]
token_string = tok[1]
start_line, start_col = tok[2]
end_line, end_col = tok[3]
ltext = tok[4]
if start_line > last_lineno:
last_col = 0
if start_col > last_col:
out += (" " * (start_col - last_col))
if token_type == tokenize.COMMENT:
pass
elif token_type == tokenize.STRING:
if prev_toktype != tokenize.INDENT:
if prev_toktype != tokenize.NEWLINE:
if start_col > 0:
out += token_string
else:
out += token_string
prev_toktype = token_type
last_col = end_col
last_lineno = end_line
return out
def stringify(data):
return remove_comments_and_docstrings(data).replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", r"\n")
def version():
version = "v1.0.2"
return "py2mel.py {}, compiled {}\n\n".format(version, datetime.datetime.today())
def python_interpret(data):
output = "// {}".format(version())
output += "python(\"{}\");".format(stringify(data))
return output
def python_shelf(data, name):
code = "# {}".format(version())
code += data
return "shelfButton -l \"{}\" -c \"{}\" -stp \"python\" -i \"daisyLarge.png\" -p `tabLayout -query -selectTab $gShelfTopLevel`;".format(name, stringify(code))
inp = args.input if args.input else sys.stdin
out = args.output if args.output else sys.stdout
data = python_shelf(inp.read(), args.shelf) if args.shelf else python_interpret(inp.read())
out.write(data)
@jamie-jenssen
Copy link

jamie-jenssen commented Jul 17, 2020

Hey I'm a 3D artist trying to get python scripts running as MEL in maya LT will this script make it possible? also the usage of this tool really is'nt making mush sense to me how do a input the files i'm trying to convert/run the code any help would be much appreciated thank you!

@internetimagery
Copy link
Author

Basically it's a simple convenience tool that wraps the python script into a large mel string, and executes it using the mel "python" command.
Will it work? Not sure. give it a shot. :)

As for usage, execute the script on the command line. Providing an input file (with python code) and an output file (to output mel into).

if you cannot execute the script directly (windows / not executable permissions / etc) you may need to invoke it with python: eg

python py2mel.py --input /path/to/source.py --output /path/to/output.mel

Replacing /path/to/source,py and /path/to/output.mel with the input and output filepaths respectively.

Let me know how it goes, if that helps, and if you have any other questions. :)

@jamie-jenssen
Copy link

Hey thanks for getting back to me I really appreciate it! I'll see if I can wrap my head around that, try it out and get back to you!

@mishominas55
Copy link

image
the path will be put here?

@internetimagery
Copy link
Author

Ah, you don't need to run it through maya script editor. If you run it as a command line script in the terminal it should work ok.

py2mel.py -input <inputFile> -output <outputFile>

If you want to use it in the script editor like that, then you'd just need to run the functions directly.

data = python_shelf(inp.read(), args.shelf) if args.shelf else python_interpret(inp.read())

Is what is being run with command line arguments added. You can replace inp.read() with a string of code from whatever file you want to use, and self.shelf you can decide yourself if True or False.

@mishominas55
Copy link

Thanks it works now, but mine issue that I want use this skript is convert Maya old phyton 2.7 to Mel for work on Maya 2022 ,but it still give me syntax error (even if I use online converter phyton 2 to 3 before, converter to mel),have u solution for that.
Best regards Mikayel

@mishominas55
Copy link

Thanks for response, it's worked now ,but Maine issue that I want use this skript ,is convert Maya old phyton skripts Mel for work in Maya 2022 .I tried to do that ,even converter phyton 2 to phyton 3 before converting ,but it still give syntax error, do u have solution for that.best regards Mikayel

@internetimagery
Copy link
Author

@mishominas55, I've made some changes. Hopefully this is python3 compatible now.

@mishominas55
Copy link

@mishominas55, I've made some changes. Hopefully, this is python3 compatible now.

it can convert if py file initially in phyton 2.7 ?

@internetimagery
Copy link
Author

No this simply is a helper to shove the python script into a mel string. ;)
You could use something from here though https://python-future.org/automatic_conversion.html

@mishominas55
Copy link

thanks so mutch

@internetimagery
Copy link
Author

Welcome. 👍

@danayad
Copy link

danayad commented May 28, 2022

Can somoeone tell me how to use this, as I'm new into maya and scripting. Thanks

@internetimagery
Copy link
Author

  • Make a new file. Name it hello.py and in the file write print("hello world")
  • Download this file next to the hello.py file
  • Start a command prompt, and switch to the folder your files are in cd /path/to/where/files/are
  • In the command prompt type python py2mel.py -i hello.py -o hello.mel
  • You should have the mel file with the python code you wrote.

@nani006
Copy link

nani006 commented Aug 10, 2022

Hi, I want to use the studio library script in MAYALT but mayaLT doesn't support py scripts so can anyone help me to convert it to MEL and make it useable in mayalt.
Thank you.

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