Menu

How do I import from other python scripts?

Help
Jeff Ward
2015-04-28
2015-05-01
  • Jeff Ward

    Jeff Ward - 2015-04-28

    In my project, PythonQt calls a python script in a resource file that needs to import from another python script which imports from another script, etc. All scripts are in the project folder and in the resource file but no syntax I've tried allows the script to be found.
    Examples:
    from otherscript import *
    from :otherscript import *
    from :/otherscript import *
    The directory containing the scripts is also in the PYTHONPATH. The scripts work if I run them directly with python. How do I import from other python scripts in the same project?

     

    Last edit: Jeff Ward 2015-04-28
  • Florian Link

    Florian Link - 2015-04-28

    You can know it, here is how it is done:

    PythonQtObjectPtr mainModule = PythonQt::self()->getMainModule();
    mainModule.evalScript(QString("import sys\n"));
    // append the Qt resource root directory to the sys.path
    mainModule.evalScript("sys.path.append(':')\n");
    // now you can import any file from the resource files
    mainModule.evalScript("import eyed3tagger\n");
    
     
  • Florian Link

    Florian Link - 2015-04-28

    Forgot to say:

      PythonQt::self()->setImporter(NULL);
    

    Is also needed, it installs an importer that supports QFile.

     

    Last edit: Florian Link 2015-04-28
  • Jeff Ward

    Jeff Ward - 2015-04-29

    Thank you. I had studied CPPPyWrapperExample and am using similar code successfully with multiple scripts as long as none of them reference another. My problem is that I can't get one script to import from another script. For example, say there are 2 scripts named script1 and script2. In script2, I would normally use something similar to "from script1 import class1" however, this doesn't work for me when using scripts in a resource. How can I do that?

     
  • Jeff Ward

    Jeff Ward - 2015-05-01

    It wasn't easy but I finally found the solution I was looking for in a PythonQt Help Forum topic from 2011 having the subject "Problems including further Python scripts".

    The scripts "script1.py" and "script2.py" are in the Scripts directory and referenced in the resource file. "script2.py" contains

    from script1 import class1
    

    I had the python syntax correct which is standard with or without PythonQt but it didn't work until I also used

    PythonQt::self()->installDefaultImporter()
    PythonQt::self()->addSysPath(":/Scripts")
    

    before loading script2.

     
  • Florian Link

    Florian Link - 2015-05-01

    You did't say that your scripts are in a subdirectory.
    My example is equivalent to your working code, except that I added ":" to the sys.path, so importing scripts that are in the root of the resources would have worked. Of course if you want to import from a subdirectory, you have to put that directory into the sys.path.

     

Log in to post a comment.