1

I had made a project manager for maya in python with Qtdesingner, in the UI, a QLineEdit authorize the user to fill a path of a script to run (the variable is: BatchRunScript) but it seems to not be possible to import a module if it's a variable (str):

import maya.utils
BatchRunScript = 'X:\PathOfTheScript\NameOfScriptToRun.ScriptToRun()'
BatchRunScriptName = BatchRunScript.replace('\\', '/').split('/')[-1]
BatchRunScriptPath = BatchRunScript.replace('\\', '/').split(BatchRunScriptName)[0]
BatchRunModuleName = BatchRunScriptName.split('.')[0]       
print 'BatchRunScriptPath: ', BatchRunScriptPath    # X:/PathOfTheScript/
print 'BatchRunScriptName: ', BatchRunScriptName    # NameOfScriptToRun.ScriptToRun()
print 'BatchRunModuleName: ', BatchRunModuleName    # NameOfScriptToRun

sys.path.append(BatchRunScriptPath)
import BatchRunModuleName
maya.utils.executeDeferred(BatchRunScriptName) 

It gives me this error:

Error: ImportError: file <maya console> line 13: No module named BatchRunModuleName

Is there another way to do run a python script from inside another?

martineau
  • 119,623
  • 25
  • 170
  • 301
Gnn
  • 107
  • 1
  • 2
  • 7

1 Answers1

1

After additional consideration, I believe @Rawing is correct and the issue you are attempting to resolve is clarified at the following link: Dynamic module import in Python

I've left my original response below for reference in case you find it helpful. The difference is, the link above shows how you can dynamically import scripts based on strings, while the code below simply executes another local python script based on a string. Import v. Execute.

Although maybe it's considered "hacky" you could always take advantage of the os library to call other scripts on the fly from within your Python client.

import os
mystr = "myscriptname.py"
os.system('Python ' + mystr)

This will allow you to call other python scripts, based on the string name of a Python file, and execute them from within your Python client.

h0r53
  • 3,034
  • 2
  • 16
  • 25
  • 1
    You shouldn't hardcode `'Python'` like that, as it may be incorrect. A better practice is to use [`sys.executable`](https://docs.python.org/3/library/sys.html#sys.executable) which will always be right. – martineau Jun 21 '17 at 16:03
  • thank you very much for your answer :) – Gnn Jun 22 '17 at 21:11