【问题标题】:How to pass newline characters in MEL variables to Python如何将 MEL 变量中的换行符传递给 Python
【发布时间】:2021-08-16 13:55:46
【问题描述】:

我已经测试了以下代码。它工作正常。

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

同样,我可以使用 Python 编写一个包含换行符的变量,如下所示。

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

但是,当我测试下面的代码时,我得到了一个错误。

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

错误信息如下:

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

我想结合使用 MEL 和 Python 将多行字符串输出到文本文件。如果可能的话,我想通过仅更改 python 代码而不更改 MEL 变量的内容来实现这一点。

我该怎么做?

我的环境是 Maya2020 + Python2。 但是,我在使用 Maya2022 + Python3 时遇到了完全相同的错误。

【问题讨论】:

  • 你得到什么错误? “一个错误”不够具体。
  • 我添加了一条错误消息。

标签: python maya mel


【解决方案1】:

您需要多次转义字符串中的“\”符号(对于 MEL、Python 和 exec):

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

或者,如果您希望保持字符串不变,请使用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)) + "\\\')\')");

顺便说一句,你不需要使用exec。这样,您将大大简化转义:

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

另一种选择是使用 MEL 进行文件输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2011-11-23
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2021-08-13
    相关资源
    最近更新 更多