title: Executing complex python scripts from within python
body: <p>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:</p>
  
  <pre><code>def executePythonScript(self, script, param):
          print 'Executing script'
          try:
              code = compile(script, '&lt;string&gt;', 'exec')
              exec code
              response = process(param)
          except Exception as ex:
              print ex
          print 'Response: ' + response
          return response
  </code></pre>
  
  <p>The "process" function is assumed to exist in the script that gets compiled and executed run-time.</p>
  
  <p>This solution works well for VERY simple scripts, like:</p>
  
  <pre><code>def process():
       return "Hello"
  </code></pre>
  
  <p>...but I'm having no luck getting more complex scripts to execute. For instance, if my script uses the json package, I get:</p>
  
  <blockquote>
    <p>global name 'json' is not defined</p>
  </blockquote>
  
  <p>Additionally, if my process function refers to another function in that same script, I'll get an error there as well:</p>
  
  <pre><code>def process():
    return generateResponse()
  
  def generateResponse():
    return "Hello"
  </code></pre>
  
  <p>...gives me an error:</p>
  
  <blockquote>
    <p>global name 'generateResponse' is not defined</p>
  </blockquote>
  
  <p>Is this an issue of namespacing? How come json (which is a standard python package) does not get recognized? Any advice would be appreciated!</p>