1

I have a python script that has a method that takes in a string that contains another python script. I'd like to execute that script, call a function in it, and then use that function's results in my main script. It currently looks something like this:

def executePythonScript(self, script, param):
        print 'Executing script'
        try:
            code = compile(script, '<string>', 'exec')
            exec code
            response = process(param)
        except Exception as ex:
            print ex
        print 'Response: ' + response
        return response

The "process" function is assumed to exist in the script that gets compiled and executed run-time.

This solution works well for VERY simple scripts, like:

def process():
     return "Hello"

...but I'm having no luck getting more complex scripts to execute. For instance, if my script uses the json package, I get:

global name 'json' is not defined

Additionally, if my process function refers to another function in that same script, I'll get an error there as well:

def process():
  return generateResponse()

def generateResponse():
  return "Hello"

...gives me an error:

global name 'generateResponse' is not defined

Is this an issue of namespacing? How come json (which is a standard python package) does not get recognized? Any advice would be appreciated!

Nik I.
  • 177
  • 1
  • 11
  • 3
    this sounds like a very very bad idea ... and almost 100% for sure there is a better way to deal with whatever you are trying to do ... why not just `from my_script import process` ? – Joran Beasley Jan 19 '17 at 22:55
  • Could you please provide a complete example of the script you are trying to execute? This could be just a missing import statement. – pelya Jan 19 '17 at 22:59
  • Thanks for the suggestions. I did end up dumping the code string into a temp file - though not ideal, it seems to work pretty well. I can't use "from myscript import process" because I only know the filename at runtime, but I've added a comment to the solution that imports a file runtime. – Nik I. Jan 25 '17 at 15:18

1 Answers1

1
import subprocess

subprocess.call(["python","C:/path/to/my/script.py"])

I would recommend against this and just use import.

This is also under the assumption that your PYTHONPATH is set in your environment variables.

Casey
  • 419
  • 5
  • 13
  • Thanks! Executing entire code from a string would be ideal, but dumping it out into a temp file seems to work just as well. I went with a solution outlined here: http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path Particularly, this one: `spec = importlib.util.spec_from_file_location("myScript", fullPath) myModule = importlib.util.module_from_spec(spec) spec.loader.exec_module(myModule)` – Nik I. Jan 25 '17 at 15:13