pythonmayamel

How to pass newline characters in MEL variables to Python


I have tested the following code. It works fine.

string $testString = "test";
python("exec(\'with open(\\\'C:/Users/username/Desktop/testString.txt\\\', \\\'w\\\') as f:\\n\t\f.write(\\\'"+$testString+"\\\')\')");

Similarly, I can use Python to write a variable that contains a newline character, as shown below.

testString = "test\ntest\n"
with open('C:/Users/username/Desktop/testString.txt', 'w') as f:
    f.write(testString)

However, when I tested the following code, I got an error.

string $testString = "test\ntest\n";
python("exec(\'with open(\\\'C:/Users/username/Desktop/testString.txt\\\', \\\'w\\\') as f:\\n\t\f.write(\\\'"+$testString+"\\\')\')");

error message is below:

# Error: line 2: EOL while scanning string literal # 

I want to use a combination of MEL and Python to output a multi-line string to a text file. If possible, I would like to achieve this by changing only the python code, without changing the contents of the MEL variables.

How can I do this?

My environment is Maya2020 + Python2. However, I get the exact same error with Maya2022 + Python3.


Solution

  • You need to escape the "\" symbol in your string several times (for MEL, for Python and for exec):

    string $testString = "test\\\\ntest\\\\n";
    python("exec(\'with open(\\\'C:/Users/username/Desktop/testString.txt\\\', \\\'w\\\') as f:\\n\t\f.write(\\\'"+$testString+"\\\')\')");
    

    Or if you wish to leave your string intact use encodeString:

    string $testString = "test\ntest\n";
    python("exec(\'with open(\\\'C:/Users/username/Desktop/testString.txt\\\', \\\'w\\\') as f:\\n\t\f.write(\\\'"+ encodeString(encodeString($testString)) + "\\\')\')");
    

    By the way, you don't need to use exec. This way you'll simplify the escaping quite a lot:

    string $testString = "some test\ntest\n";
    python("with open('C:/Users/username/Desktop/testString.txt', 'w') as f:\n\tf.write('"+ encodeString($testString) + "')");
    

    Another option would be using MEL for file output:

    string $testString = "test\ntest\n";
    $file_id = `fopen "C:/Users/username/Desktop/testString.txt" "w"`;
    fprint $file_id $testString;
    fclose $file_id;