MCPcopy Create free account
hub / github.com/MrKepzie/Natron / loadPythonScript

Method loadPythonScript

Engine/AppInstance.cpp:705–819  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

703} // AppInstance::load
704
705bool
706AppInstance::loadPythonScript(const QFileInfo& file)
707{
708 std::string addToPythonPath("sys.path.append(\"");
709
710 addToPythonPath += file.path().toStdString();
711 addToPythonPath += "\")\n";
712
713 std::string err;
714 bool ok = NATRON_PYTHON_NAMESPACE::interpretPythonScript(addToPythonPath, &err, 0);
715 assert(ok);
716 if (!ok) {
717 throw std::runtime_error("AppInstance::loadPythonScript(" + file.path().toStdString() + "): interpretPythonScript(" + addToPythonPath + " failed!");
718 }
719
720 std::string s = "app = app1\n";
721 ok = NATRON_PYTHON_NAMESPACE::interpretPythonScript(s, &err, 0);
722 assert(ok);
723 if (!ok) {
724 throw std::runtime_error("AppInstance::loadPythonScript(" + file.path().toStdString() + "): interpretPythonScript(" + s + " failed!");
725 }
726
727 QFile f( file.absoluteFilePath() );
728 if ( !f.open(QIODevice::ReadOnly) ) {
729 return false;
730 }
731 QTextStream ts(&f);
732 QString content = ts.readAll();
733 bool hasCreateInstance = content.contains( QString::fromUtf8("def createInstance") );
734 /*
735 The old way of doing it was
736
737 QString hasCreateInstanceScript = QString("import sys\n"
738 "import %1\n"
739 "ret = True\n"
740 "if not hasattr(%1,\"createInstance\") or not hasattr(%1.createInstance,\"__call__\"):\n"
741 " ret = False\n").arg(filename);
742
743
744 ok = interpretPythonScript(hasCreateInstanceScript.toStdString(), &err, 0);
745
746
747 which is wrong because it will try to import the script first.
748 But we in the case of regular scripts, we allow the user to access externally declared variables such as "app", "app1" etc...
749 and this would not be possible if the script was imported. Importing the module would then fail because it could not
750 find the variables and the script could not be executed.
751 */
752
753 if (hasCreateInstance) {
754 QString moduleName = file.fileName();
755 int lastDotPos = moduleName.lastIndexOf( QChar::fromLatin1('.') );
756 if (lastDotPos != -1) {
757 moduleName = moduleName.left(lastDotPos);
758 }
759
760 std::stringstream ss;
761 ss << "import " << moduleName.toStdString() << '\n';
762 ss << moduleName.toStdString() << ".createInstance(app,app)";

Callers

nothing calls this directly

Calls 9

toStdStringMethod · 0.80
emptyMethod · 0.80
appendMethod · 0.80
pathMethod · 0.45
openMethod · 0.45
containsMethod · 0.45
leftMethod · 0.45
isBackgroundMethod · 0.45

Tested by

no test coverage detected